简单二叉树的建立和遍历
#include<stdio.h> #include<stdlib.h> //定义节点 typedef struct BiNode{ char data; struct BiNode *lch; struct BiNode *rch; }BiNode,*BiTree; //先序建立二叉树 void Create(BiTree &T) { T =(BiNode*) malloc (sizeof(BiNode)); printf("Enter the data \n"); scanf(" %c",&T->data); if(T->data=='#') T = NULL; if(T){ Create(T->lch); Create(T->rch); } } //先序遍历 void Preorder (BiTree T) { if (T) { printf(" %c",T->data); // 访问根结点 Preorder(T->lch); // 遍历左子树 Preorder(T->rch);// 遍历右子树 } } //中序遍历 void Inorder (BiTree T) { if(T) { Inorder(T->lch); printf(" %c",T->data); Inorder(T->rch); } } //后序遍历 void Postorder (BiTree T) { if(T) { Postorder(T->lch); Postorder(T->rch); printf(" %c",T->data); } } //求二叉树深度 int TreeDepth(BiTree T) { int left=0; int right=0; if(T) { left=1+Treedepth(T->lch); right=1+Treedepth(T->rch); return left>right?left:right; } return 0; } int main() { //先序建立二叉树 printf("The fuction Create() is called.\n"); BiTree T; Create(T); //三种遍历递归算法 printf("\n"); printf("先序遍历二叉树.\n"); Preorder(T); printf("\n"); printf("中序遍历二叉树.\n"); Inorder(T); printf("\n"); printf("后序遍历二叉树\n"); Postorder(T); printf("二叉树深度:%d\n",TreeDepth(T)); printf("\n"); return 0; }
测试数据依次输入1,2,4,#,#,5,#,#,3,#,#(无,)
先序遍历输出:1,2,4,5,3
中序遍历输出:4,2,5,1,3
后序遍历输出:4,5,2,3,1
二叉树深度:3
原链接:https://www.oschina.net/code/snippet_103214_1381
请dalao不吝赐教。