Back to photostream

Balanced Binary Tree Leetcode Solution

A binary tree is Height-balanced if the difference of heights of left and right subtree of every node in the tree is at most 1. In this problem, we are going to check for a balanced binary tree.

 

Example

2

 

/

 

1

 

/

 

4

Not balanced

1

 

/

 

2 3

Balanced

Approach

It is intuitive to think that, for every node in the binary tree, we can check whether or not the left and right subtrees follow the required condition. That's the "Brute Force" method.

 

But, in order to check whether the tree is balanced, the approach can be improved on grounds of Time & Space complexities.

 

We follow an approach such that we solve the problem in a Bottom-Up manner. Check whether the subtrees of a node are itself, balanced binary trees(or not) and obtain the height of the binary tree at the same time, which can be generalized using recursion.

Algorithm(Brute Force)

 

- Start from the root and keep traversing the binary tree until the root becomes NULL

- Retrieve the height of left and right subtrees using height() function

 

- If the difference is more than '1':

 

- return false. As the tree does not satisfy the balance condition

 

- Check the balance condition for left and right subtrees recursively

 

- Print the result

 

Algorithm(Optimal)

 

- If the tree is empty, we can say it's balanced. If not, we can follow other steps:

- Create a helper function to return the "height" of a current subtree, using recursion.

 

www.tutorialcup.com/leetcode-solutions/balanced-binary-tr...

22 views
0 faves
0 comments
Uploaded on October 20, 2021