Tree, Min/Max/Balanced Depth
- 一个树depth的定义是,最深处node的depth,所以要取max.
Maximum Depth of Binary Tree
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
Minimum Depth of Binary Tree
一个意思,不过注意拐弯处如果缺了一个child并不代表valid path, 因为这个节点不是leaf node。
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (root.left != null && root.right != null) {
return Math.min(left, right) + 1;
} else if (root.left == null) {
return 1 + right;
} else {
return 1 + left;
}
}
}
Balanced Binary Tree
已经不平衡的地方直接return -1,避免去进一步做不必要的递归。
public class Solution {
public boolean isBalanced(TreeNode root) {
return helper(root) != -1;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
if (left == -1 || right == -1) {
return -1;
}
if (Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
}