8-line Java Solution, Post-Order Traversal to Get Node Depth


  • 0
    J
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root == null) return true;
            return (Math.abs(depth(root.left)-depth(root.right)) <= 1) && (isBalanced(root.left)) && (isBalanced(root.right));
        }
        
        private int depth(TreeNode node) {
            if(node == null) return 0;
            int left = depth(node.left);
            int right = depth(node.right);
            return Math.max(left,right) + 1;
        }
    }
    

Log in to reply
 

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