C#, double-recursion, 165ms,easy understand


  • 0
    T
    public class Solution {
        public bool IsBalanced(TreeNode root)
            {
                if (root == null)
                    return true;
                if (root.left != null && root.right != null)
                    return Math.Abs(Depth(root.left) - Depth(root.right)) > 1 ? false : IsBalanced(root.left)&& IsBalanced(root.right);
                else if (root.left != null)
                    return Depth(root.left) >0? false : IsBalanced(root.left);
                else if (root.right != null)
                    return Depth(root.right) > 0 ? false : IsBalanced(root.right);
                else
                    return true;
            }
    
            static int Depth(TreeNode root)
            {
                if (root.left != null && root.right != null)
                    return 1 + Math.Max(Depth(root.left), Depth(root.right));
                else if (root.left != null)
                    return 1+ Depth(root.left);
                else if (root.right != null)
                    return 1 + Depth(root.right);
                else
                    return 0;
            }
    }

Log in to reply
 

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