C# - DFS solution


  • 1
        public bool IsBalanced(TreeNode root) 
        {
            return Height(root).Item2;
        }
        
        public Tuple<int, bool> Height(TreeNode node)
        {
            if (node == null) return new Tuple<int, bool>(0, true);
            
            Tuple<int,bool> left = Height(node.left);
            if (!left.Item2) return new Tuple<int,bool>(-1, false);
            
            Tuple<int,bool> right = Height(node.right);
            if (!right.Item2) return new Tuple<int,bool>(-1, false);
            
            int height = 1 + Math.Max(left.Item1, right.Item1);
            bool balanced = Math.Abs(left.Item1 - right.Item1) <= 1;
            return new Tuple<int,bool>(height, balanced);
        }
    

Log in to reply
 

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