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

kunkun 2014-11-09

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

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

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

 

// 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;
}

相关推荐