  # How to verify whether a binary tree is balanced tree?

182 views
How to verify whether a binary tree is balanced tree? posted Dec 12, 2013

A balanced binary tree is a binary tree in which the depth of the two subtrees of every node differ by 1 or less. or we can say

``````public static int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}

public static boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int heightDiff = getHeight(root.left) - getHeight(root.right);
if (Math.abs(heightDiff) > 1) {
return false;
}
else {
return isBalanced(root.left) && isBalanced(root.right);
}
}
`````` answer Dec 12, 2013
–1 vote

A tree is said to be balanced if it height at every level is 1,0,-1. Height is calculated by subtracting the number of elements on left by number of elements on right side of node answer May 17, 2016
Similar Questions
``````                    50                      50
/  \                    /  \
20     30              30   20
Sample Tree<---   /  \                       /  \   ----> Mirror image
70      80                   80   70
/  \    \                    /    /  \
10  40     60                60   40   10
``````
``````      40
/\
20 60
/\  \
10 30  80
/   /\
25  70 90
\
75

longest path
25 30 20 40 60 80 70 75