您的位置:首页 > 其它

LeetCode_Balanced Binary Tree

2015-09-04 19:23 295 查看
原题链接:

class Solution {
public:
bool isBalanced(TreeNode* root) {
bool flag = true;
if(!root) //空树
return true;

start(root,flag);
return flag;
}
void start(TreeNode* root,bool &flag)
{
if(!root)
{
return;
}
int leftPath = 0,rightPath = 0;
leftPath = searchPath(root->left);//找左子树的层数
rightPath = searchPath(root->right);//找右子树的层数
if(abs(leftPath-rightPath) > 1)
{
flag = false;
return;
}
if(root->left)
start(root->left,flag);
if(root->right)
start(root->right,flag);

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