【刷題】牛客CD172-判斷二叉樹是否為平衡二叉樹
阿新 • • 發佈:2021-01-03
題目描述 平衡二叉樹的性質為: 要麼是一棵空樹,要麼任何一個節點的左右子樹高度差的絕對值不超過
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;
}