Check if a tree is balanced. Why should we check MinDepth? Please help me.
Solution found in CareerCup
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
public static int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
public static boolean isBalanced(TreeNode root){
return (maxDepth(root) - minDepth(root) <= 1);
}
Why not the following solution work?? Please explain in detail
public static int maxDepth(TreeNode root){
if(root==null)
return 0;
return 1+ Math.max(maxDepth(root.left), maxDepth(root.right));
}
public static boolean isBalanced(TreeNode root){
return (maxDepth(root.left) - maxDepth(root.right) <=1);
}
as condition for balanced tree is difference between minimum and maximum height of tree should be 0 or 1
- Crazy Tesla January 22, 2013