+ Reply to Thread
Results 1 to 3 of 3

Thread: Balanced Tree

  1. #1
    Krazy Guest

    Balanced Tree

    Given a Binary Tree, check whether it is balanced or not. A tree is balanced if difference between height of left and right subtree is not more than one.

  2. #2
    Krazy Guest
    Code:
    #include <iostream>
    
    using namespace std;
    
    struct binTree {
    	int data;
    	struct binTree* left;
    	struct binTree* right;
    };
    
    typedef struct binTree* Tree;
    
    Tree insert(Tree T, int x)
    {
    	if (T == NULL) {
    		T = (Tree)malloc(sizeof(struct binTree));
    		T->data = x;
    		T->left = T->right = NULL;
    	} else if (x > T->data) {
    		T->right = insert (T->right, x);
    	} else if (x < T->data) {
    		T->left = insert(T->left, x);
    	}
    	return T;
    }
    
    int height(Tree T)
    {
    	if (T == NULL)
    		return 0;
    	else {
    		int l = height(T->left);
    		int r = height(T->right);
    
    		return (1+ (l>r?l:r));
    	}
    }
    
    bool isBalanced(Tree T)
    {
    	if (T == NULL)
    		return true;
    	else if (abs(height(T->left) - height(T->right)) > 1)
    		return false;
    	else
    		return isBalanced(T->left) && isBalanced(T->right);
    }
    Please let me know if there is any bug in this code.

  3. #3
    Anurag Aggarwal is offline Junior Member
    Join Date
    Jul 2011
    Posts
    1
    why isBalanced is making recursive calls.
    height(Tree T) is a recursive function which returns height of the tree.
    By calculating height of left and right tree using height(Tree T) and comparing them should also work?

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts