手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2014-11-09] 来源:Linux社区  作者: tjssehaige [字体:大 中 小]

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

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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-11/109192.htm

linux
相关资讯       二叉树 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款