您的位置:首页 > 职场人生

剑指offer面试题之判断一颗二叉树是不是平衡二叉树

2016-03-18 14:32 501 查看
1,题目:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

2,思想:

考虑树为空的情况;

(1)算左右子树的深度,再相减,若等于-1,1和0即为平衡二叉树,若不是则为否。

则问题就转化为了求一颗树的深度了。

在牛客网上的编码为:

class Solution {
public:
int depthofnode(TreeNode* p){
if (p == NULL)
{
return 0;
}
queue<TreeNode*> q;
q.push(p);
int level = 0;
int length = 0;
while (!q.empty())
{
level++;
length = q.size();
while (length--)
{
TreeNode* temp = q.front();
q.pop();
if (temp->left)
{
q.push(temp->left);
}
if (temp->right)
{
q.push(temp->right);
}
}
}
return level;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if (pRoot == NULL)
{
return true;
}
int leftdepth = depthofnode(pRoot->left);
int rightdepth = depthofnode(pRoot->right);
int balance = leftdepth - rightdepth;
if (balance == 0)
{
return true;
}
else if (balance == -1)
{
return true;
}
else if (balance == 1)
{
return true;
}
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: