Leetcode

Balanced Binary Tree

  • Time:O(n\log n)
  • Space:O(h)

C++

class Solution {
 public:
  bool isBalanced(TreeNode* root) {
    if (!root)
      return true;
    return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 &&
           isBalanced(root->left) &&
           isBalanced(root->right);
  }

 private:
  int maxDepth(TreeNode* root) {
    if (!root)
      return 0;
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
  }
};

JAVA

class Solution {
  public boolean isBalanced(TreeNode root) {
    if (root == null)
      return true;
    return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 &&
           isBalanced(root.left) &&
           isBalanced(root.right);
  }

  private int maxDepth(TreeNode root) {
    if (root == null)
      return 0;
    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
  }
}

Python

class Solution:
  def isBalanced(self, root: Optional[TreeNode]) -> bool:
    if not root:
      return True

    def maxDepth(root: Optional[TreeNode]) -> int:
      if not root:
        return 0
      return 1 + max(maxDepth(root.left), maxDepth(root.right))

    return abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 and \
        self.isBalanced(root.left) and self.isBalanced(root.right)