Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.

C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
10  bool isBalancedHelper(TreeNode* root, int& height)
11  {
12      if(root==NULL)
13      {
14          height=0;
15          return true;
16      }
17      int left;
18      int right;
19      bool leftBalanced=isBalancedHelper(root->left,left);
20      bool rightBalanced=isBalancedHelper(root->right,right);
21      if((left>right+1)||(right>left+1))
22         return false;
23      height=left>right?left+1:right+1;
24      return leftBalanced&&rightBalanced;
25  }
26 class Solution {
27 public:
28     bool isBalanced(TreeNode *root) {
29         // Start typing your C/C++ solution below
30         // DO NOT write int main() function
31         int height=0;
32         return isBalancedHelper(root,height);
33     }
34 };
Advertisements
This entry was posted in Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s