C语言 二叉树构建与前中后序遍历

闲来无事,随手练练好久不用的数据结构编码,写一个创建二叉树和遍历二叉树的小程序,如有错误还请指正。

程序测试输入:1 2 3 -1 -1 4 -1 -1 5 -1 -1 -1 (“-1”输入作为标识符),构建的二叉树结构如下图所示:


// 20130425.cpp : Defines the entry point for the console application.
/*@author: tjssehaige 
   @date: 2012/05/01
   @notes: Create binary tree as well as traverse tree by preorder, inorder and postorder
   @version: 1.0.0
*/
//

#include "stdafx.h"
#include <stdio.h>
#include <malloc.h>
/*Node structure for binary tree*/
typedef struct node{
	int data; /*data field*/
	node* left; /*left child pointer*/
	node* right; /*right child pointer*/
}BNode, *BTree; 

/*Create binary tree with numeric input*/
void CreateBinaryTree(BTree& tree){	
		int inputdata;
		scanf("%d",&inputdata);
		if(-1==inputdata){
			tree=NULL;
		}else{
			if (!(tree=(BNode*)malloc(sizeof(BNode)))){
				return;
			}
			/*recursively invoke function CreateBinaryTree*/
			tree->data=inputdata;
			CreateBinaryTree(tree->left);
			CreateBinaryTree(tree->right);
		}
		return;
}
/*PreOrder Traverse*/
void preorderTraverse(BTree tree){
	if (tree!=NULL){
		printf("%d ", tree->data);
	}
	if (tree->left!=NULL){
		preorderTraverse(tree->left);
	}
	if (tree->right){
		preorderTraverse(tree->right);
	}
}
/*InOrder Traverse*/
void inorderTraverse(BTree tree){
	if (tree->left!=NULL){
		inorderTraverse(tree->left);
	}
	if (tree!=NULL){
		printf("%d ", tree->data);
	}
	if (tree->right!=NULL){
		inorderTraverse(tree->right);
	}
}
/*PostOrder Traverse*/
void postorderTraverse(BTree tree){
	if (tree->left!=NULL){
		postorderTraverse(tree->left);
	}
	if (tree->right!=NULL){
		postorderTraverse(tree->right);
	}
	if (tree!=NULL){
		printf("%d ", tree->data);
	}
}
int _tmain(int argc, _TCHAR* argv[]){
	BTree tree;
	CreateBinaryTree(tree);
	printf("PreOrder Traverse:");
	preorderTraverse(tree);
	printf("\n");
	printf("InOrder Traverse:");
	inorderTraverse(tree);
	printf("\n");
	printf("PostOrder Traverse:");
	postorderTraverse(tree);
	printf("\n");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值