歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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

二叉樹的常見問題及其解決程序 http://www.linuxidc.com/Linux/2013-04/83661.htm

【遞歸】二叉樹的先序建立及遍歷 http://www.linuxidc.com/Linux/2012-12/75608.htm

在JAVA中實現的二叉樹結構 http://www.linuxidc.com/Linux/2008-12/17690.htm

【非遞歸】二叉樹的建立及遍歷 http://www.linuxidc.com/Linux/2012-12/75607.htm

二叉樹遞歸實現與二重指針 http://www.linuxidc.com/Linux/2013-07/87373.htm

二叉樹先序中序非遞歸算法 http://www.linuxidc.com/Linux/2014-06/102935.htm

輕松搞定面試中的二叉樹題目 http://www.linuxidc.com/linux/2014-07/104857.htm

Copyright © Linux教程網 All Rights Reserved