-
树的先序遍历:先访问树根,再访问左子树,最后访问右子树
void Show_tree(T_node *root)//先序遍历 37 { 38 if(root!=NULL)//为空时返回 39 { 40 printf("%c",root->data);//从根节点出发 41 Show_tree(root->l_child);//递归调用自己,以左孩子再次作为根节点 42 Show_tree(root->r_child);//递归调用自己,以右孩子再次作为根节点 43 } 44 return; 45 }
-
树的中序遍历:先访问左子树,再访问树根,最后访问右子树
void Show_tree2(T_node *root)//中序遍历 48 { 49 if(root!=NULL)//为空时返回 50 { 51 Show_tree2(root->l_child);//先从左孩子出发 52 printf("%c",root->data);//左孩子访问完了后再访问根节点 53 Show_tree2(root->r_child);//最后右孩子 54 } 55 return; 56 }
-
树的后续遍历:先访问右子树,再访问左子树,最后访问树跟
void Show_tree3(T_node *root)//后序遍历 59 { 60 if(root!=NULL)//为空时返回 61 { 62 Show_tree3(root->l_child);//先从左孩子出发 63 Show_tree3(root->r_child);//左孩子完了后,再右孩子 64 printf("%c",root->data);//最后根节点 65 } 66 return; 67 }
-
树的层次遍历:从上到下,从左到右,节点依次入队出队
void Show_Floor_tree(T_node *root)//层次遍历 69 { 70 T_node *stack[N];//初始化一个同类型数组 71 int front,rear;//定义入队和出队节点 72 front=rear=0;//初始时没有数据入队和出队的节点都为0 73 T_node *p,*q;//初始化两个同类型指针 74 p=root;//指向根节点 75 while(p!=NULL) 76 { 77 printf("%c",p->data);//输出当前节点 78 q=p->l_child; 79 if(q!=NULL)//左孩子不为空就入队 80 { 81 stack[rear++]=q; 82 } 83 q=p->r_child; 84 if(q!=NULL)//右孩子不为空就入队 85 { 86 stack[rear++]=q; 87 } 88 if(front!=rear)//队列不为空就出队 89 { 90 p=stack[front++]; 91 }
注意:不管哪一种遍历,总是先左后右。
先序遍历: 先根 再左 再右
中序遍历: 先左 再根 再右
后序遍历: 先左 再右 再根
完整代码如下:
头文件:
7 #ifndef __LINKTREE__ 8 #define __LINKTREE__ 9 10 #define N 100 11 typedef int data_t; 12 typedef struct tree_node 13 { 14 data_t data; 15 struct tree_node *l_child; 16 struct tree_node *r_child; 17 }T_node; 18 19 extern T_node *create_linktree();//创建二叉树 20 extern void Show_tree(T_node *root);//先序遍历 21 extern void Show_tree2(T_node *root);//中序遍历 22 extern void Show_tree3(T_node *root);//后序遍历 23 extern void Show_Floor_tree(T_node *root);//层次遍历 24 25 26 #endif
函数实现:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "linktree.h" T_node *create_linktree() { char ch; scanf("%c",&ch); T_node *root; if(ch =='#') { return NULL; } else { root=(T_node *)malloc(sizeof(T_node)); if(NULL==root) { printf("malloc failed!\n"); return NULL; } root->data=ch; root->l_child=create_linktree();//递归创建左孩子 root->r_child=create_linktree();//递归创建右孩子 return root; } } void Show_tree(T_node *root)//先序遍历 { if(root!=NULL) { printf("%c",root->data); Show_tree(root->l_child); Show_tree(root->r_child); } return; } void Show_tree2(T_node *root)//中序遍历 { if(root!=NULL) { Show_tree2(root->l_child); printf("%c",root->data); Show_tree2(root->r_child); } return; } void Show_tree3(T_node *root)//后序遍历 { if(root!=NULL) { Show_tree3(root->l_child); Show_tree3(root->r_child); printf("%c",root->data); } return; } void Show_Floor_tree(T_node *root)//层次遍历 { T_node *stack[N];//初始化一个同类型数组 int front,rear;//定义入队和出队节点 front=rear=0;//初始时没有数据入队和出队的节点都为0 T_node *p,*q;//初始化两个同类型指针 p=root;//指向根节点 while(p!=NULL) { printf("%c",p->data);//输出当前节点 q=p->