bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 110. Balanced Binary Tree

110. Balanced Binary Tree

Leetcode Solutions

Bottom-up Recursion Approach

  1. Define a helper function checkHeight that returns the height of the subtree if it is balanced, otherwise returns -1 as an error code.
  2. For each node, recursively call checkHeight on its left and right children.
  3. If the absolute difference in heights of the left and right subtrees is more than 1, or if either subtree is unbalanced (indicated by a -1 return value), return -1.
  4. If the subtree is balanced, return the height of the subtree, which is 1 plus the maximum of the heights of the left and right subtrees.
  5. The main function isBalanced calls checkHeight on the root and returns true if the result is not -1, indicating the tree is balanced.
UML Thumbnail

Top-down Recursion Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...
bugfree Icon
OR