题目描述 平衡二叉树的性质为: 要么是一棵空树,要么任何一个节点的左右子树高度差的绝对值不超过
1。给定一棵二叉树,判断这棵二叉树是否为平衡二叉树。 一颗树的高度指的是树的根节点到所有节点的距离中的最大值。输入描述: 第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。 以下 n 行每行三个整数
fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
输出描述: 如果是平衡二叉树则输出 “true”,否则输出 “false”。
输入
3 1
1 2 3
2 0 0
3 0 0
输出
true
#include<bits/stdc++.h>
using namespace std;
struct TreeNode{
int value;
TreeNode *left,*right;
TreeNode(int value_):value(value_),left(NULL),right(NULL){}
};
map<int,TreeNode*>mp;
int maxDepthSub = 0;
int depthGap(TreeNode*root){
if(root==NULL)
return 0;
int left = depthGap(root->left);
int right = depthGap(root->right);
maxDepthSub = max(maxDepthSub, abs(left - right));
return max(left, right) + 1;
}
TreeNode* createRoot(int value){
TreeNode* root;
if(mp.count(value)==0){
root = new TreeNode(value);
mp[value] = root;
}else{
root = mp[value];
}
return root;
}
int main(){
int n,r;
cin>>n>>r;
TreeNode* root = new TreeNode(r);
mp[r] = root;
int fa,lch,rch;
for(int i=0;i<n;i++){
scanf("%d %d %d",&fa,&lch,&rch);
TreeNode* cur = createRoot(fa);
if(lch){
cur->left = createRoot(lch);
}else{
cur->left = NULL;
}
if(rch){
cur->right = createRoot(rch);
}else{
cur->right = NULL;
}
}
if(root==NULL)
cout<<"true"<<endl;
depthGap(root);
if(maxDepthSub<=1)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
return 0;
}