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 of every node never differ by more than 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
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
bool helper(TreeNode* node, int& height){ | |
if(node==NULL){ | |
height=0; | |
return true; | |
} | |
bool rt=true; | |
bool lt=true; | |
int lheight=0; | |
int rheight=0; | |
if(node->left!=NULL) | |
lt=helper(node->left, lheight); | |
if(node->right!=NULL) | |
rt=helper(node->right, rheight); | |
if(lt&&rt&&abs(rheight-lheight)<=1){ | |
height=max(lheight, rheight)+1; | |
return true; | |
} | |
return false; | |
} | |
bool isBalanced(TreeNode* root) { | |
int height=0; | |
bool res=helper(root, height); | |
return res; | |
} | |
}; |
No comments:
Post a Comment