public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
一个意思,不过注意拐弯处如果缺了一个 child 并不代表是 valid path,因为这个节点可能不是 leaf node.
public class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null) return minDepth(root.right) + 1;
if(root.right == null) return minDepth(root.left) + 1;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
public class Solution {
public boolean isBalanced(TreeNode root) {
return (getDepth(root) != -1);
}
private int getDepth(TreeNode root){
if(root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
if(left == -1 || right == -1) return -1;
if(Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
}