基本的一个binarytree的遍历程序

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

// 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!!!!!!!!!!!*/

/*preorder(0);*/

inorder(0);

/*postorder(0);*/

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.

*/

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航