标签:
问题描述: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.
解决方案:
/**
* 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 isBalanced(TreeNode* root) {
if(root==NULL)
return true;
int dep = 0;
return isBalanced(root,dep);
}
bool isBalanced(TreeNode* root ,int& deepth)
{
if(root == NULL)
{
deepth = 0;
return true;
}
int depLeft=0;
int depRight=0;
bool left = isBalanced(root->left,depLeft);
bool right = isBalanced(root->right,depRight);
deepth = max(depLeft,depRight)+1;
if(abs(depLeft-depRight)>1)
{
return false;
}
return left&&right;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/leosha/article/details/46685909