您的位置:首页 > 其它

LeetCode Balanced Binary Tree

2015-01-19 10:51 183 查看
题目

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 binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool innerIsBalanced(TreeNode *root,int &height)	//判断平衡,并求高度
{
if(root==NULL)	//空
{
height=0;
return true;
}
int height_left,height_right;	//左子树高度,右子树高度
if(!innerIsBalanced(root->left,height_left))	//判断左子树平衡,求高度
return false;
if(!innerIsBalanced(root->right,height_right))	//判断右子树平衡,求高度
return false;
height=max(height_left,height_right)+1;	//计算当前子树的高度
return abs(height_left-height_right)<=1;	//判断平衡性
}
bool isBalanced(TreeNode *root) {
int height;
return innerIsBalanced(root,height);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: