#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
class btree
{
public:
int value;
btree *lchild;
btree *rchild;
};
btree * createbtree(btree * root,int *num,int &index) //前序递归创建树
{
if(num[index]==0)
{
return NULL;
}
root = new btree;
root->value=num[index];
root->lchild = createbtree(root->lchild,num,++index);
root->rchild = createbtree(root->rchild,num,++index);
return root;
}
void pre(btree *root) //前序输出
{
if(root==NULL)
return ;
cout<<root->value<<" ";
pre(root->lchild);
pre(root->rchild);
}
void in(btree *root) //中序输出
{
if(root==NULL)
return ;
in(root->lchild);
cout<<root->value<<" ";
in(root->rchild);
}
void print(btree *root,int h)
{
if(root != NULL)
{
print(root -> rchild,h+1);
for(int i=0; i<h; i++)
cout << " ";
cout << root -> value;
print(root -> lchild,h+1);
}
cout << endl;
}
int deep(btree *root) //树的深度
{
int l,r;
if(root==NULL)
return 0;
l = deep(root->lchild);
r = deep(root->rchild);
return max(l,r)+1;
}
int sum(btree *root) //节点个数
{
int l,r;
if(root==NULL)
return 0;
l = sum(root->lchild);
r = sum(root->rchild);
return l+r+1;
}
void change(btree * & root) //交换左右节点
{
if(root==NULL)
return ;
btree *t;
t=root->lchild;
root->lchild = root->rchild;
root->rchild = t;
change(root->lchild);
change(root->rchild);
}
void getleaves(btree *root,int &ans) //求叶子节点的个数
{
if(root==NULL)
return ;
if(root->lchild==NULL&&root->rchild==NULL)
{
ans++;
return ;
}
getleaves(root->lchild,ans);
getleaves(root->rchild,ans);
}
int main()
{
queue<btree *> aqueue;
int index=0;
int num[]={1,2,4,8,100,0,0,0,9,0,0,5,10,0,0,11,0,0,3,6,12,0,0,13,0,0,7,14,0,0,15,0,0};
btree *root=NULL;
root = createbtree(root,num,index);
pre(root);cout<<endl;
in(root);cout<<endl;
cout<<deep(root)<<endl;
cout<<sum(root)<<endl;
print(root,1);
change(root);
print(root,1);
aqueue.push(root);
while(!aqueue.empty())
{
btree *temp = aqueue.front();
cout<<temp->value<<" ";
aqueue.pop();
if(temp->lchild!=NULL)
aqueue.push(temp->lchild);
if(temp->rchild!=NULL)
aqueue.push(temp->rchild);
}
cout<<endl;
int ans=0;
getleaves(root,ans);
cout<<ans<<endl;
return 0;
}
二叉树的基本操作
最新推荐文章于 2022-01-30 12:23:49 发布