1 struct node { 2 int value; 3 struct node* lson; 4 struct node* rson; 5 }; 6 typedef struct node* tree;
先序遍历:根结点 -> 左子树 -> 右子树
1 void PreorderTraversal(tree root) { 2 if(root) { 3 printf("%d ", root->value); 4 PreorderTraversal(root->lson); 5 PreorderTraversal(root->rson); 6 } 7 }
中序遍历:左子树 -> 根结点 -> 右子树
1 void InorderTraversal(tree root) { 2 if(root) { 3 InorderTraversal(root->lson); 4 printf("%d ", root->value); 5 InorderTraversal(root->rson); 6 } 7 }
后序遍历:左子树 -> 右子树 -> 根结点
1 void PostorderTraversal(tree root) { 2 if(root) { 3 PostorderTraversal(root->lson); 4 PostorderTraversal(root->rson); 5 printf("%d ", root->value); 6 } 7 }
层序遍历:
1 #define maxSize 100050 2 void LevelordetTraversal(tree root) { 3 if (root == NULL) { 4 return ; 5 } 6 7 struct node queue[maxSize] = {0}; 8 int head = 0, tail = 1; 9 queue[head] = (*root); 10 11 while (head < tail) { 12 printf("%d", queue[head].value); 13 14 if (queue[head].lson) { 15 queue[tail++] = (*queue[head].lson); 16 } 17 if (queue[head].rson) { 18 queue[tail++] = (*queue[head].rson); 19 } 20 21 ++head; 22 } 23 }