您的位置:首页 > 其它

LeetCode:Balanced Binary Tree

2013-11-24 15:21 316 查看
题目链接

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.

分析:判断一颗二叉树是否是平衡的,dfs递归求解,递归的过程中顺便求得树的高度 本文地址

/**
* 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 isBalanced(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root == NULL)return true;
if(height(root) == -1)return false;
else return true;
}
//若root是平衡树,那么返回树的高度,否则返回-1
int height(TreeNode *root)
{
if(root->left == NULL && root->right == NULL)return 1;
int leftHeight = 0, rightHeight = 0;
if(root->left)
leftHeight = height(root->left);
if(leftHeight == -1)return -1;
if(root->right)
rightHeight = height(root->right);
if(rightHeight == -1)return -1;
if(abs(leftHeight-rightHeight) > 1)return -1;
return 1+max(leftHeight, rightHeight);
}
};


【版权声明】转载请注明出处:/article/4879654.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: