数据结构之二叉树的递归创建、递归遍历
2013-03-23 13:02
525 查看
// Tree.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "stdio.h" #include "iostream" using namespace std; typedef struct node { int data; struct node *lchild; struct node *rchild; }BiTNode, *BiTree; int CreateBiTree(BiTree &T); int CreateBiTree(BiTree &T,int &index); void PreOrder(BiTree root); void InOrder(BiTree root); void PostOrder(BiTree root); int element[]={3,7,3,2,1,0,0,7,0,0,0,8,0,10,0,0,17,18,0,0,19,0,27,0,0}; static int index=0; int _tmain(int argc, _TCHAR* argv[]) { BiTree tree; // 递归的创建二叉树 CreateBiTree(tree,index); printf("创建二叉树完毕\n"); printf("先序遍历\n"); PreOrder(tree); printf("\n"); printf("中序遍历二叉树\n"); InOrder(tree); printf("\n"); printf("二叉树的后序遍历\n"); PostOrder(tree); printf("\n"); system("pause"); return 0; } // 按照先序顺序,递归的创建二叉树 int CreateBiTree(BiTree &T) { int data; scanf("%d",&data); if (data==0) // 0代表子节点为空 { T=NULL; } else { T=(BiTree)malloc(sizeof(BiTNode)); if (!T) { return -1; } else { T->data=data; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } } return 1; } // 按照先序顺序,递归的创建二叉树,通过数组输入二叉树中的数据 int CreateBiTree(BiTree &T,int &index) { int data=element[index]; if (data==0) // 0代表子节点为空 { T=NULL; } else { T=(BiTree)malloc(sizeof(BiTNode)); if (!T) { return -1; } else { T->data=data; CreateBiTree(T->lchild,++index); CreateBiTree(T->rchild,++index); } } return 1; } // 先序遍历二叉树 void PreOrder(BiTree root) { if (root!=NULL) { printf("%3d",root->data); PreOrder(root->lchild); PreOrder(root->rchild); } } // 中序遍历 void InOrder(BiTree root) { if (root!=NULL) { InOrder(root->lchild); printf("%3d",root->data); InOrder(root->rchild); } } // 后序遍历 void PostOrder(BiTree root) { if (root!=NULL) { PostOrder(root->lchild); PostOrder(root->rchild); printf("%3d",root->data); } }
相关文章推荐
- 数据结构复习:链式二叉树创建和递归遍历
- 数据结构-----创建/递归非递归遍历二叉树
- 数据结构和算法--二叉树创建和递归遍历
- 【数据结构】二叉树的递归与非递归创建和遍历
- 数据结构--树和二叉树--二叉树的创建和遍历(递归和非递归方式)
- 数据结构(二叉树系列)先序创建三种遍历和求深度(递归实现)
- 二叉树的创建及递归和非递归遍历
- 二叉树的创建与遍历(递归版本)
- [C++]数据结构:链表二叉树的创建与四种遍历方式
- 二叉树的递归创建以及前序,中序,后序遍历
- 二叉树创建及遍历算法(递归及非递归)
- 二叉树的创建 先序 中序 后续 递归和非递归遍历
- 二叉树的创建与遍历(递归版本)
- 二叉树创建及遍历算法(递归及非递归)
- 采用二叉链表结构实现二叉树,并以递归遍历思想实现二叉树的创建、二叉树的遍历(先序、中序、后序和层次遍历)
- PHP数据结构之九 PHP储存二叉树,二叉树的创建与二叉树的基本操作 遍历二叉树算法
- 【数据结构】二叉树的遍历(递归与非递归)
- 二叉树的创建以及递归非递归遍历
- 数据结构:二叉树(前,中,后,层次)非递归遍历。
- C语言学习历程(十八) 数据结构二叉树的创建、遍历、深度等算法