Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

Definition of a height-balanced binary tree: a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example

A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7
A: true          B: false

Analysis

Again we try D&C first. Assign tasks to leftSubtree and rightSubtree to see if they are both balanced then report to the root. If either left or right is not balanced, then the whole tree is not balanced. Or the height difference is greater than 1 then also not balanced.

Code

Very similar to maxDepth problem. Need to check if leftSub == -1 or rightSub == -1 or height diff > 1

Analysis #2

From an industry stand point, -1 is very unclear and can be hard to maintain afterward. Java doesn't support returning a tuple (That's why python is op for interview). We need a structure to hold our information. A structure is useful when we need to return 2 or more values.

Better Code

Time Complexity

The time is O(V) because we visit each node exactly once.

Last updated