#include <iostream>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
bool is_banance_tree(node* r, int& height)
{
if(r == NULL)
{
height = 0;
return true;
}
int lchild_height, right_height;
bool l_ban, r_ban;
l_ban = is_banance_tree(r->lchild, lchild_height);
r_ban = is_banance_tree(r->rchild, right_height);
if(!l_ban || !r_ban)
return false;
if(abs(lchild_height-right_height)>1)
return false;
height = max(lchild_height, right_height) + 1;
return true;
}
void build_tree(node*& root ,int *a, int& i)
{
if(a==NULL)
return ;
if(a[i] == -1)
{
root = NULL;
return ;
}
root = new node;
root->data = a[i];
build_tree(root->lchild ,a, ++i);
build_tree(root->rchild ,a, ++i);
}
void pre_traverse(node* root)
{
if(root==NULL)
cout<<-1<<" ";
else
{
cout<<root->data<<" ";
pre_traverse(root->lchild);
pre_traverse(root->rchild);
}
}
int main()
{
int a[] = {8,4,1,-1,-1,7,6,5,-1,-1,-1,-1,12,-1,-1};
node* root;
int i=0;
build_tree(root, a, i);
pre_traverse(root);
bool b;
b = is_banance_tree(root, i);
if(b)
cout<<endl<<"yes"<<endl;
else
cout<<endl<<"no"<<endl;
return 0;
}
判断平衡二叉树,创建二叉树,先序遍历二叉树
最新推荐文章于 2022-10-12 13:54:47 发布