4ms Accepted Java Recursive Solution By Jasonchu1313


  • 0
    J
    class Solution {
         //recurisively determine whether the tree is a height-balanced binary tree
        public boolean isBalanced(TreeNode root){
            if(root!=null){
                if(Math.abs(treeHeight(root.right)-treeHeight(root.left))>1){
                    return false;
                }else{
                    if(root.left == null && root.right !=null){
                        return isBalanced(root.right);
                    }else if(root.left != null && root.right ==null){
                        return isBalanced(root.left);
                    }else if(root.left != null && root.right !=null){
                        return isBalanced(root.left) && isBalanced(root.right);
                    }else{
                        return true;
                    }
                }
            }else{
                return true;
            }
            
        }
        //given the tree's root get the height of the tree
        public int treeHeight(TreeNode root){
            if(root == null){
                return -1;
            }else{
                return 1+Math.max(treeHeight(root.left),treeHeight(root.right));
            }
        }
    }
    

    Worth to mention that if I use if to manually compare the treeHeight(root.left) and the treeHeight(root.right), the test case 225 will have time limit error, but when I change to the library function Math.max() to choose the larger branch, I will successfully pass all the test cases.
    0_1516000662413_testcases.png


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.