您的位置:首页 > 编程语言 > C语言/C++

Balanced Binary Tree

2015-07-19 23:36 260 查看
一、题目要求

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.

二、代码实现

bool isBalanced(TreeNode* root) {
if(root==NULL)
return true;

int left=maxDepth(root->left);
int right=maxDepth(root->right);
if(abs(left-right)>1)
return false;

return isBalanced(root->left)&&isBalanced(root->right);
}

int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
int left=1+maxDepth(root->left);
int right=1+maxDepth(root->right);
return left>right?left:right;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息