基本的一個binarytree的遍歷程序

// binarytree.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <stdio.h>
struct node
{
 int value;
 int right;
 int left;
}tree[15];
void inorder(int root){
 if(tree[root].left!=-1)
  inorder(tree[root].left);
 printf("%d ",tree[root].value);
 if(tree[root].right!=-1)
  inorder(tree[root].right);
}
void preorder(int root)
{
 printf("%d ",tree[root].value);
 if(tree[root].left!=-1)
  preorder(tree[root].left);
 if(tree[root].right!=-1)
  preorder(tree[root].right);
}
void postorder(int root)
{
 if(tree[root].left!=-1)
  postorder(tree[root].left);
 if(tree[root].right!=-1)
  postorder(tree[root].left);
 printf("%d ",tree[root].value);
}
main()
{
 /*
 first to initalized the matrix of the tree
 */
 for(int i=0;i<15;i++){
  tree[i].value=i;
 }
 tree[0].left=1;
 tree[0].right=2;
 tree[1].left=3;
 tree[1].right=4;
 tree[2].left=5;
 tree[2].right=6;
 tree[3].left=7;
 tree[3].right=8;
 tree[4].left=-1;
 tree[4].right=-1;
 tree[5].left=9;
 tree[5].right=10;
 tree[6].left=11;
 tree[6].right=12;
 tree[7].left=13;
 tree[7].right=14;
 tree[8].left=-1;
 tree[8].right=-1;
 tree[9].left=-1;
 tree[9].right=-1;
 tree[10].left=-1;
 tree[10].right=-1;
 tree[11].left=-1;
 tree[11].right=-1;
 tree[12].left=-1;
 tree[12].right=-1;
 tree[13].left=-1;
 tree[13].right=-1;
 tree[14].left=-1;
 tree[14].right=-1;
    /*the order functions are put here!!!!!!!!!!!*/
printf("copyrights by fish&SEhome============================>use it freely");
printf("this is preorder's result:/n");
 preorder(0);
printf("/n");
printf("this is inorder's result:/n");
 inorder(0);
printf("/n");
printf("this is postorder's result:/n");
 postorder(0);
printf("/n");
printf("========================================================");
 system("pause");
}
/*
The structure of the tree is listed here:
                      0
    1             2
          3        4       5        6
     7       8   -1 -1   9    10   11   12
13     14 
@Vincent
the tree has been stored in the array,every element is a node and it contains 3 fields
they are Value,Left,Right means the node's value and it's left & right subtree's root.
If you want to use order function,remove the // before the function.
*/

 

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