来源:互联网 发布:数控r角怎么编程 编辑:程序博客网 时间:2024/05/17 08:05

二叉树  建立  与 中序输出(顺序的。。。) 求树的深度
#include<iostream>
using namespace std;
typedef int element;
typedef struct Tree
{
   element data;
   Tree *lchild;
   Tree *rchild;
}Tree1;

typedef Tree1*  Tree2;

void insert(Tree2& proof,Tree2& tree)
{
 if(proof==NULL)
   proof=tree;
 else
 {
  if(tree->data<=proof->data)
   insert(proof->lchild ,tree);
  else
   insert(proof->rchild ,tree);

 }
 
}

void visit(Tree2 tree)
{
   if(tree==NULL)
   return;
   visit(tree->lchild);
   cout<<tree->data<<" ";
   visit(tree->rchild);
}

void Deepth(Tree2 tree,int h,int &depth)  // 求二叉树的深度。 // depth 随时 更新,当某节点无任何孩子时候,返回该节点的上一层
{
  if(tree)
  {
   if(h>depth)
    depth=h;
   Deepth(tree->lchild ,h+1,depth);
   Deepth(tree->rchild ,h+1,depth);
  }
}


int Deepth1(Tree2 tree)  //  一直 递归,在递归到终端节点时 开始返回  深度值随着返回 而累加,每层取左右的大值,一直到根节点。
{
   if(!tree)  return 0;
   else
   {
   int hl=Deepth1(tree->lchild);
    int hr=Deepth1(tree->rchild);
    if(hl>=hr)return hl+1;
    else
     return hr+1;
   }
}

 

 

========线索二叉树 ,用双向链表实现,设置一个头指针,通过中序遍历过程形成双向循环链表=============

 

void InThreading(Tree2& p,Tree2&pre)// 初始化时,参数为,根节点 和 头结点
                                       // 之后 便是 某一节点 与 此节点的前一个节点
{                                    

 if(p)
 {
   InThreading(p->lchild,pre);

   p->pred=pre; pre->succ=p;  // 设置前驱与后继

   pre=p;            // 更新pre ,即为下一次节点的pred域做准备

   InThreading(p->rchild,pre);
 }
}

 

void INorder(Tree2&h,Tree2 T,Tree2&pre)
{
 h=new Tree;//h为头指针
 h->lchild=T; h->rchild=NULL;//设置头指针的。。。
 
 if(!T)
 {h->pred=h;h->succ=h;}
 
 else
 {
  pre=h;
  InThreading(T,pre);
  pre->succ=h; h->pred=pre;// 处理最后一个节点的 succ 域和 头结点的pred域
 }
}

 

void visit1(Tree2 t,Tree2& H)
{
 t=(*t).succ;
 while(1)
 {
  cout<<(*t).data<<" ";
  t=(*t).succ;
  if(t==H)
   break;
 }
 
}

 

 

 

int main()
{
 Tree2 tree,proof;
 proof=NULL;tree=NULL;
 element x;

 while(cin>>x,x!=-1)
 {
    tree=new Tree;
                   tree->data=x;
    tree->lchild =NULL;
    tree->rchild =NULL;
    insert(proof,tree);
 }
              visit(proof); 
              Deepth(proof,1,depth);
             cout<<depth<<endl;
             cout<<Deepth1(proof);
 return 0;
}

 

 

 

原创粉丝点击