您的位置:首页 > 其它

Balanced Binary Tree

2016-06-04 16:19 246 查看
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.

思路:给定一棵树,判断这个树是不是平衡二叉树。平衡二叉树的定义如下:

(1)对于根节点root来说,其左右子树的高度差的绝对值小于等于1

(2)左子树为平衡的

(3)右子树为平衡的

代码如下:

/**
* 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)
return true;
return fabs(getTreeHeigh(root->left)-getTreeHeigh(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
}

int getTreeHeigh(TreeNode *root) //返回一棵树的高度是多少
{
if(root==NULL)
return 0;
return max(getTreeHeigh(root->left),getTreeHeigh(root->right))+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: