基本的一个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.
*/

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值