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

程序员面试题精选100题(60)-判断二叉树是不是平衡的

2011-07-31 13:24 483 查看

题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。例如下图中的二叉树就是一棵平衡二叉树:






#include<iostream>
usingnamespacestd;

structBTNode{
BTNode*Left;
BTNode*Right;
intvalue;
BTNode(intval=0)
:value(val){}
};

BTNode*CreateTree(){
intdata;
cin>>data;
BTNode*root;

if(-1==data)
returnNULL;
else{
root=newBTNode(data);
root->Left=CreateTree();
root->Right=CreateTree();
}
returnroot;
}

boolIsBalancedBT(BTNode*pRoot,int*pDepth){
if(!pRoot){
*pDepth=0;
returntrue;
}
intleft,right;
if(IsBalancedBT(pRoot->Left,&left)
&&IsBalancedBT(pRoot->Right,&right)){
intdiff=left-right;
if(diff<=1&&diff>=-1){
*pDepth=1+(left>right?left:right);
returntrue;
}
}
returnfalse;
}

boolIsBalanced(BTNode*root){
intdepth=0;
returnIsBalancedBT(root,&depth);
}

voidprintTree(BTNode*root){
if(!root)return;
printTree(root->Left);
cout<<root->value<<"";
printTree(root->Right);
return;
}

intmain(){
BTNode*root=CreateTree();
printTree(root);
cout<<endl;
if(IsBalanced(root))
cout<<"Thebinarytreeisbalanced!"<<endl;

return0;
}

参考文献:http://zhedahht.blog.163.com/blog/static/25411174201142733927831/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐