**Objective:** Given a binary tree, Find whether if a Given Binary Tree is Balanced?

**What is balanced Tree: **A balanced tree is a tree in which difference between heights of sub-trees of any node in the tree is not greater than one.

**Input:** A Binary Tree

**Output: **True and false based on whether tree is balanced or not.

**Example: **

**Approach : **

**Naive Approach: **

*for each node of the tree, get the height of left subtree and right subtree and check the difference , if it is greater than 1, return false.*

**Complete Code:**

**Better Solution:**

- Recursion
- Post order traversal technique
- Travel all the way down to leaf nodes and then go up.
- while going up, calculate the left and right subtree height.
- If the difference between them is greater than 1, return -1.
- Else Max(leftHeight, rightHeight) +1 .
- Here you wont actually calculate the height of the subtrees by calling function, instead you will store the height at each level and when you go one level up, you add one to it.
*So Time complexity is not O(N^2) but it will ne only O(N) but it will have space complexity as O(h) where h is the height of the tree*

**Complete Code:****Output**:Is Tree Balanced : true Is Tree Balanced : false

why do you need to chek if the right or left height is -1? it’s possible that the height would be -1?

Sorry for the confusion but here Its just a way to represent in this problem when tree is not balanced, return -1. you can use some other value as well

if(result>0){

return true;

I think the condition must be updated to result >= 0 as a null tree cannot be qualified as unbalanced

totally agree 🙂

The picture you have made to represent a binary tree is not a functional binary tree… You have a node that has a value greater than 5, but instead of linking it to the right of the ‘5’ node, you’re linking it to the left.

its totally fine..because the topic is “Find whether if a Given Binary Tree is Balanced?” it’s binary tree and not binary search tree…so it doesn’t matter….he must have done this for the sake of simple example.

I didn’t notice that. I thought it read Binary Search Tree. My apologies to the OP.

thank you…this is what exactly i was looking for…god bless you.

I think the complexity of the first algorithm is NlogN. I got the recurrence relation as T(n) = 1 + n + 2T(n/2)