先知道原理,代码会在后面补充(其实是我还没看懂代码。。。)
二叉树的遍历主要有三种:
(1)先(根)序遍历(根左右)
(2)中(根)序遍历(左根右)
(3)后(根)序遍历(左右根)
相关例子:二叉树的先序、中序、后序遍历序列
题目: 先序 A B D E H I C F K G
中序 D B H E I A F K C G
画出二叉树:
代码更新:
#include <stdio.h> typedef struct NodeList { char val; struct NodeList* left; struct NodeList* right; }Node; void prelist(Node* node) //根左右 { if(node!=NULL) { printf("%c ", node->val); prelist(node->left); prelist(node->right); } } void midlist(Node* node) //左根右 { if (node != NULL) { midlist(node->left); printf("%c ", node->val); midlist(node->right); } } void lastlist(Node* node) //左右根 { if (node != NULL) { lastlist(node->left); lastlist(node->right); printf("%c ", node->val); } } int main() { Node n1, n2, n3, n4,n5,n6,n7,n8,n9,n10; n1.val = 'A'; n2.val = 'B'; n3.val = 'C'; n4.val = 'D'; n5.val = 'E'; n6.val = 'F'; n7.val = 'G'; n8.val = 'H'; n9.val = 'I'; n10.val = 'K'; n1.left = &n2; n1.right = &n3; n2.left = &n4; n2.right = &n5; n3.left = &n6; n3.right = &n7; n4.left = NULL; n4.right = NULL; n5.left = &n8; n5.right = &n9; n6.left = NULL; n6.right = &n10; n7.left = NULL; n7.right = NULL; n8.left = NULL; n8.right = NULL; n9.left = NULL; n9.right = NULL; n10.left = NULL; n10.right = NULL; prelist(&n1);//先序遍历 printf(" "); midlist(&n1);//中序遍历 printf(" "); lastlist(&n1);//后序遍历 return 0; }
打印: