二叉树结构常用操作

来源:互联网 发布:淘宝居家日用类目 编辑:程序博客网 时间:2024/06/06 01:17
我写的是不带头节点的二叉树链式结构。
#include<iostream>
#include<queue>
using namespace std;
#define maxn 1005
int a[maxn],b[maxn];
struct Tree
{
 int v;
 Tree* lc,*rc;
};
queue<Tree *> q;
Tree* root;
int max(int x,int y)
{
 return x>y?x:y;
}
Tree* build(int *a,int *b,int n)
{
    int i;
 Tree* ss;
 for(i=0;i<n;i++)
 {
  if(a[0]==b[i])
  {
        ss=(Tree* )malloc(sizeof(Tree));
  ss->v=b[i];
  ss->lc=build(a+1,b,i);
  ss->rc=build(a+i+1,b+i+1,n-i-1);
  return ss;
  }
 }
        return NULL;
}
void xianxu_bianli(Tree* T)
{
 if(T==NULL) return ;
 cout<<T->v;
 xianxu_bianli(T->lc);
 xianxu_bianli(T->rc);
}
void zhongxu_bianli(Tree* T)
{
 if(T==NULL) return ;
 zhongxu_bianli(T->lc);
        cout<<T->v;
 zhongxu_bianli(T->rc);
}
void houxu_bianli(Tree* T)
{
 if(T==NULL) return;
 houxu_bianli(T->lc);
 houxu_bianli(T->rc);
 cout<<T->v<<' ';
}
void bfs(Tree* T)
{
 if(!T) return;
 q.push(T);
 while(!q.empty())
 {
  Tree *u=q.front();
  q.pop();
  cout<<u->v;
  if(u->lc!=NULL) q.push(u->lc);
  if(u->lc!=NULL) q.push(u->rc);
 }
}
int Nodecount(Tree* T)
{
 if(T==NULL) return 0;
 return Nodecount(T->lc)+Nodecount(T->rc)+1;
}
int Treedepth(Tree *T)
{
 if(T==NULL) return 0;
 return max(Treedepth(T->lc),Treedepth(T->rc))+1;
}
void remove_tree(Tree* T)
{
 if(T==NULL) return;
 remove_tree(T->lc);
 remove_tree(T->rc);
 delete(T);
 T=NULL;
}
void copy_tree(Tree* T,Tree *NT)
{
        if(!T) {NT=NULL;return;}
        NT->v=T->v;
        copy_tree(T->lc,NT->lc);
        copy_tree(T->rc,NT->rc);
}
Tree* translate(Tree* T)    //交换左右子树
{
        if(!T||(T->lc==NULL&&T->rc==NULL))
        return T;
        else
        {
        Tree* p;
        p=T->lc;
        T->lc=T->rc;
        T->rc=p;
        T->lc=translate(T->rc);
        T->rc=translate(T->lc);
        return T;
        }
}
int main()
{
 int n,i;
 while(scanf("%d",&n)!=0)
 {
  for(i=0;i<n;i++)
  {
   cin>>a[i];
  }
  for(i=0;i<n;i++)
  {
   cin>>b[i];
  }
  root=build(a,b,n);
  houxu_bianli(root);
 }
 return 0;
}

原创粉丝点击