6.2二叉树的遍历

来源:互联网 发布:下载默默聊天软件 编辑:程序博客网 时间:2024/06/16 14:20

6.2二叉树的遍历

二叉树的遍历(规定由左及右)3种方式,包括

(1)LDR中序,InorderTraverse;

(2)DLR先序,PreorderTraverse;

(3)LRD后序,PostorderTraverse。


(0)同二叉树的创建一样,二叉树的遍历采用递归的方式。

(1)LDR中序,InorderTraverse

void inorder(BiTree t){if(t){inorder(t->lchild);printf("%c ",t->data);inorder(t->rchild);}}

(2)DLR先序,PreorderTraverse

void preorder(BiTree t){if(t){printf("%c ",t->data);preorder(t->lchild);preorder(t->rchild);}}

(3)LRD后序,PostorderTraverse

void postorder(BiTree t){if(t){postorder(t->lchild);postorder(t->rchild);printf("%c ",t->data);}}

(4)万事俱备,只欠东风了。现在我们就检验一下上一章二叉树的创建。

<span style="white-space:pre"></span>/*样例输入:abc##de#f##g###*/#include<iostream>#include<stdlib.h>#define len (sizeof(BiNode))#define OK 1typedef struct bintree{struct bintree *lchild;char data;struct bintree *rchild;}BiNode, *BiTree;BiTree t;//头结点指针int bintree_creat(BiTree &q);void visit(BiTree t);void preorder(BiTree t);void inorder(BiTree t);void postorder(BiTree t);int main(){printf("input node data :");bintree_creat(t);visit(t);return 0;}int bintree_creat(BiTree &q){char n;n = getchar();if(n == '#')q = NULL;else{q = (BiTree )malloc(len);q->data = n;bintree_creat(q -> lchild);bintree_creat(q -> rchild);}return OK;}void visit(BiTree t){int i;while(1){printf("\n\ninput 1 : preorder the tree !\ninput 2 : inorder the tree !\ninput 3 : postorder the tree !\ninput 0 to exit\n\n");scanf("%d",&i);switch (i){case 1 :preorder(t);  break;case 2 :inorder(t);   break;case 3 :postorder(t); break;case 0 :exit(0);default:printf("input error !");break;}}}void preorder(BiTree t){if(t){printf("%c ",t->data);preorder(t->lchild);preorder(t->rchild);}}void inorder(BiTree t){if(t){inorder(t->lchild);printf("%c ",t->data);inorder(t->rchild);}}void postorder(BiTree t){if(t){postorder(t->lchild);postorder(t->rchild);printf("%c ",t->data);}}

递归方式二叉树的遍历就这样完成了。2014/10/20



0 0
原创粉丝点击