【问题描述】
给出一个二叉树,判断其是否是一个高度平衡的二叉树。其中 数值为-1 代表该节点为NIL
【输入形式】
第一行:输入节点的数量
第二行:各个节点的数值
【输出形式】
若为高度平衡的二叉树,输出1,否则输出0
【样例输入】
7
3 9 20 -1 -1 15 7
【样例输出】
1
【样例输入】
9
1 2 2 3 3 -1 -1 4 4
【样例输出】
0
【样例说明】
在上述样例输入中 1 2 2 3 3 -1 -1 4 4所示树的形状为
1
/ \
2 2
/ \ / \
3 3 NIL NIL
/ \
4 4
思路
分为两部分:建立树,判断。
层次遍历建树用栈实现,判断用递归。
#include <iostream>
#include <queue>
#include<vector>
using namespace std;
class BinaryTree{
private:
struct Node{//二叉树的结点类
Node*left,*right;
int data;
Node():left(NULL),right(NULL){}
Node(int item,Node *L=NULL,Node *R=NULL):data(item),left(L),right(R){}
};
Node *root;//二叉树的根节点
int height(Node*t,int &flag){
if (t==NULL) return 0;
if (abs(height(t->left,flag)-height(t->right, flag))>1) {
flag=0;
}
return max(height(t->left,flag),height(t->right,flag))+1;
}
public:
void createTree(){
Node*tmp;int k=1;
queue<Node *>que;
int x=0,ldata=0,rdata=0,n=0;
cin>>n;
cin>>x;
root=new Node(x);
que.push(root);
while(k<n){
tmp=que.front();
que.pop();
cin>>ldata>>rdata;k+=2;
if (ldata!=-1) {
que.push(tmp->left=new Node(ldata));
}
if (rdata!=-1) {
que.push(tmp->right=new Node(rdata));
}
}
}
int judge(){
int flag=1;
height(root, flag);
return flag;
}
};
int main() {
BinaryTree T;
T.createTree();
cout<<T.judge();
return 0;
}
若将-1改成任意符号
void createTree(Type flag){
Node*tmp;
queue<Node *>que;
Type x,ldata,rdata;
cout<<"\n输入根节点:";
cin>>x;
root=new Node(x);
que.push(root);
while(!que.empty()){
tmp=que.front();
que.pop();
cout<<"\n输入"<<tmp->data<<"的两个儿子"<<flag<<"表示空结点";
cin>>ldata>>rdata;
if (ldata!=flag) {
que.push(tmp->left=new Node(ldata));
}
if (rdata!=flag) {
que.push(tmp->right=new Node(rdata));
}
}
cout<<"create completed!\n";
}