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

编程实现判断一棵二叉树是否是平衡二叉树

2014-05-16 15:38 274 查看


Balanced Binary Tree


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.
思路:遍历这棵二叉树,每访问一个结点都要判断这个结点的子树是否是平衡的,如果平衡则继续访问结点;否则,可以判断这个二叉树是不平衡的。如果遍历完所有结点都没有找到不平衡的结点,说明该二叉树是平衡二叉树。

class Solution {
public:
bool isBalanced(TreeNode *root) {
stack<TreeNode *> s;//用于先序遍历
TreeNode * pCur = root;
int m, n;
while(pCur || !s.empty())
{
m = height(pCur->left);
n = height(pCur->right);
if(m-n > 1 || m-n < -1)//找到不平衡点,结束
return 0;
s.push(pCur);
pCur = pCur->left;
//如果当前结点pCur为NULL且栈不空,则将栈顶结点出栈,
//同时置其右孩子为当前结点,循环判断,直至pCur不为空
while(!pCur && !s.empty())
{
pCur = s.top();
s.pop();
pCur = pCur->right;
}
}
return 1;//没找到不平衡点
}

int height(TreeNode *root)
{
if(!root)
return -1;//空树高度定义为-1
else if(!root->left && !root->right)//树只有一个根结点
return 0;//只有一个结点的树,高度定义为0
else
return max(height(root->left), height(root->right)) + 1;
}

int max(int a, int b)//求两个值中的较大值
{
return a>b?a:b;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: