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

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

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

二叉树的常见问题及其解决程序

【递归】二叉树的先序建立及遍历

Java中实现的二叉树结构

【非递归】二叉树的建立及遍历

二叉树递归实现与二重指针

二叉树先序中序非递归算法

轻松搞定面试中的二叉树题目

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/24369940f0f6a3880a5baa7b2afb9307.html