top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to verify whether a binary tree is balanced tree?

+4 votes
135 views
How to verify whether a binary tree is balanced tree?
posted Dec 12, 2013 by Mona Sharma

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

2 Answers

+2 votes

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 by Luv Kumar
–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 by Shaik Farheen
Similar Questions
+6 votes
                    50                      50
                   /  \                    /  \
                  20     30              30   20
Sample Tree<---   /  \                       /  \   ----> Mirror image
               70      80                   80   70
              /  \    \                    /    /  \  
             10  40     60                60   40   10
+5 votes
      40
      /\
     20 60
     /\  \
   10 30  80
      /   /\
     25  70 90
           \
           75

longest path 
25 30 20 40 60 80 70 75 
Answer
    25 ----> 75
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...