Last active
February 1, 2019 19:06
-
-
Save bansalayush/d7c736b2d3a6c3f6d7f240ae40353b99 to your computer and use it in GitHub Desktop.
Calculating height of a Binary Tree :) Check if a tree is balanced or not :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Diff in left and right height should be less than or equal to 1. | |
int traverse(node){ | |
if(node == null) | |
return 0; | |
int leftHeight = traverse(node->left); | |
int rightHeight = traverse(node->right); | |
isBalanced(leftHeight,rightHeight,node); | |
return max(leftHeight,rightHeight) + 1; | |
} | |
void isBalanced(int left,int right,node){ | |
int diff = |left - right|; | |
if(diff > 1) | |
{ un-balanced at node} | |
else | |
{ balanced } | |
} | |
/////////////////////EXAMPLE////////////////// | |
a | |
/ \ | |
b c | |
/ \ / \ | |
d e f i | |
/ \ | |
g h | |
The tree above is balanced ( don't believe me, dry run it once ) | |
//////////////EXAMPLE///////////////////// | |
a | |
/ \ | |
b c | |
/ \ / \ | |
d e f i | |
/ \ | |
g h | |
/ | |
j | |
This tree is un-balanced at `c` ... Why ???? because it left height is 3 and it's right height is 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
What is Height of a tree ???? | |
Height is measured in upward direction. The longest path from leaf to the root is called height of a tree. | |
Height of leaf node is 1 | |
int traverse(node){ | |
if(node == null) | |
return 0; | |
int leftHeight = traverse(node->left); | |
int rightHeight = traverse(node->right); | |
int height = max(leftHeight,rightHeight) + 1; | |
return height; | |
} | |
///////////EXAMPLE TREE////////////////// (because i need one every time :P ) | |
a | |
/ \ | |
b c | |
/ \ / \ | |
d e f i | |
/ \ | |
g h | |
from above function we get Height of tree as 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment