110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
题目解析:
- 可以用递归求左右子树的高度差
- 使用-1表示该子树不平衡
代码:
class Solution {
public boolean isBalanced(TreeNode root) {
return depth(root) == -1 ? false : true;
}
public int depth(TreeNode root) {
if (root == null) return 0;
int left = depth(root.left);
int right = depth(root.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
}
257. Binary Tree Paths
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
题目解析:
- 求二叉树所有路径使用DFS比较合适
代码:
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
dfs(root, new ArrayList<>(), result);
return result;
}
public void dfs(TreeNode root, List<String> path, List<String> result) {
path.add(String.valueOf(root.val));
if (root.left == null && root.right == null) {
String s = path.stream().collect(Collectors.joining("->"));
result.add(s);
}
if (root.left != null) {
dfs(root.left, path, result);
}
if (root.right != null) {
dfs(root.right, path, result);
}
path.remove(path.size() - 1);
}
}
404. Sum of Left Leaves
Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
题目解析:
- 节点是否为叶子节点并且为父节点的左节点, 可使用flag标记是否为左节点
代码:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return dfs(root, false);
}
public int dfs(TreeNode root, boolean isLeft) {
if (root == null) {
return 0;
}
int sum = 0;
if (root.left != null) {
sum += dfs(root.left, true);
}
if (root.right != null) {
sum += dfs(root.right, false);
}
if (isLeft && root.left == null && root.right == null) {
sum += root.val;
}
return sum;
}
}
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
int sum = 0;
if (root.left != null) {
if (isLeaf(root.left)) {
sum += root.left.val;
} else {
sum += sumOfLeftLeaves(root.left);
}
}
if (root.right != null) {
sum += sumOfLeftLeaves(root.right);
}
return sum;
}
public boolean isLeaf(TreeNode root) {
if (root.left == null && root.right == null) {
return true;
}
return false;
}
}