题目描述
给定一棵二叉树的中序和层序输出,判断是否为平衡二叉树的。如果是,输出YES如果不是输出NO。
输入
树结点个数
中序遍历序列
层序遍历序列
输出
是否是平衡二叉树的判断结论
样例输入
样例1:
3
1 2 3
2 1 3
样例2:
4
1 2 3 4
1 2 3 4
样例输出
样例1:
YES
样例2:
NO
代码如下:
#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
int layer[10000], in[10000];
int n;
template<typename T>
struct TreeNode
{
T data;
TreeNode<T>* lchild;
TreeNode<T>* rchild;
TreeNode(TreeNode<T>* lc=NULL, TreeNode<T>* rc=NULL):lchild(lc),rchild(rc) {}
TreeNode(const T& elem, TreeNode<T>* lc=NULL, TreeNode<T>* rc=NULL):data(elem),lchild(lc),rchild(rc) {}
};
template<typename T>
class BinaryTree
{
private:
TreeNode<T>* root;
public:
BinaryTree( int ll,int lr,int inl,int inr)
{
root=TreeCreate(ll,lr,inl,inr);
}
TreeNode<T>* TreeCreate(int ll, int lr, int inl, int inr)
{
if(inl>inr)
return NULL;
TreeNode<T> *t = new TreeNode<T>();//因为每次递归返回的是一个结点,所以需要每次分配空间
int i,j;
bool f;
for(i = ll; i<=lr; i++)
{
f = false;
for(j = inl; j<=inr; j++)
{
if(layer[i] == in[j])
{
t->data = in[j];
t->lchild = NULL;
t->rchild = NULL;
f = true;
break;
}
}
if(f)//如果找到了结点就出去
break;
}
if(!f)
return NULL;
if(j > inl)//递归如果位置大于中序左边的位置
t->lchild = TreeCreate(0, n-1, inl, j-1);//为什么是从零开始,这里的n是全局变量。注意左孩子,从找到的根节点划分左子树。
if(j < inr)
t->rchild = TreeCreate(0, n-1, j+1, inr);
return t;
}
TreeNode<T>* getNode()
{
return root;
}
int GetDepth(TreeNode<T>* r)
{
int depth;
int ld, rd;
if(!r)
return 0;
else
{
ld = GetDepth(r->lchild);
rd = GetDepth(r->rchild);
depth = ld > rd ? ld :rd;
return depth+1;
}
}
int IsAVL(TreeNode<T>* root)
{
if(root==NULL)
return 1;
int ldepth = GetDepth(root->lchild);
int rdepth = GetDepth(root->rchild);
int abs_depth = abs(ldepth-rdepth);
return (abs_depth <= 1) && IsAVL(root->lchild)&& IsAVL(root->rchild);
}
};
int main()
{
cin>>n;
int i;
for(i=0; i<n; i++)
cin>>in[i];
for( i=0; i<n; i++)
cin>>layer[i];
BinaryTree<int> bt(0,n,0,n);
if(bt.IsAVL(bt.getNode())==0)
cout<<"No";
else
cout<<"Yes";
return 0;
}