二叉树表示
typedef struct TNode *Position;
typedef Position BinTree; // 二叉树类型
struct TNode { // 树的定义
ElementType Data; // 结点数据
BinTree Left; // 指向左子树
BinTree Right; // 指向右子树
};
一、中序遍历
void InorderTraversal(BinTree BT)
{
if (BT) {
InorderTraversal(BT->Left);
// 此处假设对BT结点的访问就是打印数据
printf("%d", BT->Data); // 假设数据为整型
InorderTraversal(BT->Right);
}
}
void InOrderTraversal(BinTree BT)
{
// 利用堆栈进行非递归遍历
BinTree T=BT;
Stack S = CreateStack(MaxSize); // 创建并初始化堆栈
while (T || !IsEmpty(S)) {
while (T) { // 一直向左并将沿途结点压入堆栈
Push(S, T);
T = T->Left;
}
if (!IsEmpty(S)) {
T = Pop(S); // 结点弹出堆栈
printf("%5d", T->Data); // (访问)打印结点
T = T->Right; // 转向右子树
}
}
}
二、先序遍历
void PreorderTraversal(BinTree BT)
{
// 递归遍历
if (BT) {
// 此处假设对BT结点的访问就是打印数据
printf("%d", BT->Data); // 假设数据为整型
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
}
void PreorderTraversal(BinTree BT)
{
// 利用堆栈进行非递归遍历
BinTree T=BT;
Stack S = CreateStack(MaxSize); // 创建并初始化堆栈
while (T || !IsEmpty(S)) {
while (T) { // 一直向左并将沿途结点压入堆栈
Push(S, T);
printf("%5d", T->Data); // (访问)打印结点
T = T->Left;
}
if (!IsEmpty(S)) {
T = Pop(S); // 结点弹出堆栈
T = T->Right; // 转向右子树
}
}
}
三、后序遍历
void PostorderTraversal(BinTree BT)
{
if (BT) {
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf("%d", BT->Data);
}
}
- 根据非递归的先序遍历和中序遍历的结果(数组),可以获得后序遍历的结果
void solve(int preL, int inL, int postL, int n)
{ // preL是先序遍历数组的下标,inL是中序遍历数组的下标,postL是后序遍历数组的下标
if (n == 0) return;
if (n == 1) {post[postL] = pre[preL]; return;}
root = pre[preL];
post[postL+n-1] = root; // 将先序遍历中的根结点,放入后序遍历的数组中
for (i=0; i<n; i++) // 在中序遍历的结果中找到根结点的数组下标
if (in[inL+i] == root) break;
L = i; R = n-L-1;
solve(preL+1, inL, postL, L);
solve(preL+L+1, inL+L+1, pstL+L, R);
}