先序遍歷二叉樹的遞歸算法

//// 2.cpp : 定義控制檯應用程序的入口點。
////
//
//#include "stdafx.h"
//using namespace std;
//
//int _tmain(int argc, _TCHAR* argv[])
//{
// cout<< "dfdf";
// return 0;
//}
//

//#include <stdio.h>
#include "stdafx.h"
#include <malloc.h>

typedef struct node{
 int data;
 struct node *lchild,*rchild;
}*treetp,tree;
treetp create (treetp t,int c);
void print1(treetp);
void print2(treetp);
void print3(treetp);
int number=0;
void main()
{
 treetp t=0,r;
 r=create (t,0);
 printf("/n前序排列 :");
 print1 (r);
 printf("/n中序排列 :");
 print2 (r);
 printf("/n後序排列 :");
 print3 (r);
}

treetp create(treetp t,int c)
{
 treetp p,di; // p用來指向所要分配的結點,di用來指向p的雙親
 do{ // do—while結構用來構造二叉數,直到輸入0爲止
  scanf("%d",&c); // 輸入葉子結點的數據
  if (t==0) // 如果這是創建的第一個結點(根),則t指向這個結點(根)
  {
   t=(treetp)malloc(sizeof(tree));
   t->lchild=t->rchild=0;
   t->data=c;
  }
  else // 否則,按二叉排序樹的構造方法構造樹
  { p=t; // 先讓p指向根
  while(p!=0) // 如果p 不空,則按二叉排序樹的查找順序來查找新的結點位置
  {
   di=p; // 在p指向下一個結點之前,用di保存當前p的位置
   if(c<(p->data)) // 如果輸入的結點比p指向的結點小
    p=p->lchild; // p指向當前p的左孩子
   else
    p=p->rchild; // 否則p指向當前p的右孩子
  }
  // 此處已經退出 while(p!=0) 這個循環,表明已經找到輸入的結點合適的位置了,
  // 這個位置或者是di的左孩子,或者是di的右孩子
  if(c<(di->data)) // 如果輸入的結點比di小,將輸入的結點添加在di左孩子
  {
   treetp NEWdi=(treetp) malloc(sizeof(tree));
   NEWdi->lchild=NEWdi->rchild=0;
   NEWdi->data=c;
   di->lchild=NEWdi;
  }
  else // 否則將輸入的結點添加在di的又孩子
  {
   treetp NEWdi=(treetp) malloc(sizeof(tree));
   NEWdi->lchild=NEWdi->rchild=0;
   NEWdi->data=c;
   di->rchild=NEWdi;
  }
  }
  ++number; // 結點數+1
 }while(c!=0);
 printf("葉子的數量:%d",number);
 return t;
}
void print1(treetp t) // 先序遍歷二叉樹的遞歸算法:根,左,右
{
 if (t!=0)
 {
  printf("%d ",t->data);
  print1(t->lchild);
  print1(t->rchild);
 }
}
void print2(treetp t) // 中序遍歷二叉樹的遞歸算法:坐,根,右
{
 if (t!=0)
 {
  print2(t->lchild);
  printf("%d ",t->data);
  print2(t->rchild);
 }
}
void print3(treetp t) // 後續遍歷二叉樹的遞歸算法:坐,右,根
{
 if (t!=0)
 {
  print3(t->lchild);
  print3(t->rchild);
  printf("%d ",t->data);
 }

發佈了31 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章