二叉树的遍历大致能分为以下几种
1.前序:根 左 右
2.中序:左 根 右
3.后序:左 右 根
4.层序:从根开始一层一层的向下
如上图访问顺序:
前序:1 2 3 N N N 4 5 N N 6 N N
中序:N 3 N 2 N 1 N 5 N 4 N 6 N
后序:N N 3 N 2 N N 5 N N 6 4 1
层序:1 2 4 3 5 6
ps:这里的N是NULL
前中后都是以递归的方式,层序就和堆差不多是一层一层的访问
理解了上面的代码就可以尝试写出他的代码了
//BinTree.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
typedef int BinTreeType;
struct BinTreeNode
{struct BinTreeNode* left;struct BinTreeNode* right;BinTreeType val;};
typedef struct BinTreeNode BTNode;BTNode* BuyBTNode(BinTreeType val);
BTNode* CreateTree();
void PreOrder(BTNode* root);
void InOrder(BTNode* root);
void PostOrder(BTNode* root);
void PreOrder(BTNode* root)
{if (root == NULL){printf("NULL ");return ;}printf("%d ", root->val);PreOrder(root->left);PreOrder(root->right);
}
void InOrder(BTNode* root)
{if (root == NULL){printf("NULL ");return;}InOrder(root->left);printf("%d ", root->val);InOrder(root->right);
}
void PostOrder(BTNode* root)
{if (root == NULL){printf("NULL ");return;}PostOrder(root->left);PostOrder(root->right);printf("%d ", root->val);
}