JAVA solution. I'm guessing I could switch between bottom up/top down through this way?


  • 0
    R

    Its a 10 line code with 2 ms runtime.

    I am thinking if I can switch between top down and bottom up by simply changing the return value of isBalanced from the existing one to the one that is commented out?

    Thanks for any comments/suggestions.

        import java.math.*;
        public class Solution {
            public boolean isBalanced(TreeNode root) {
                if (root == null) return true;
    //Top down?        
                //return Math.abs(checkheight(root.left, 0) - checkheight(root.right, 0)) <= 1 ? isBalanced(root.left) && isBalanced(root.right) : false;
    //Bottom up?
                return isBalanced(root.left) && isBalanced(root.right) ? Math.abs(checkheight(root.left, 0) - checkheight(root.right, 0)) <= 1 : false;
            }
            public int checkheight(TreeNode Node, int currentHeight){
                return Node == null ? currentHeight : Math.max(checkheight(Node.left, currentHeight + 1), checkheight(Node.right, currentHeight + 1));
            }
        }

Log in to reply
 

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