typedef struct node{ //二叉树标准链式存储结构
char data; //节点值
struct node *lchild; //左子节点
struct node *rchild; //右子节点
} NODE; //二叉树的结构
前序(递归)
void preorder_with_recursion(NODE *root) {
printf("%c", root->data);
if (root->lchild) preorder_with_recursion(root->lchild);
if (root->rchild) preorder_with_recursion(root->rchild);
}
前序(非递归,用栈实现)
void preorder_without_recursion(NODE *root) {
NODE *stack[MAXN]; //栈存放指向结点的指针
int top, i;
if (root == NULL) return ; //空树
stack[0] = root; //根入栈
top = 1; //top指向下次入栈的位置
while (top > 0) {
root = stack[--top]; //栈顶元素出栈,root指向当前出栈的结点
printf("%c", root->data);
if (root->rchild) stack[top++] = root->rchild; //右孩子先入栈
if (root->lchild) stack[top++] = root->lchild;
}
}
中序(递归)
void inorder_with_recursion(NODE *root) {
if (root->lchild) inorder_with_recursion(root->lchild);
printf("%c", root->data);
if (root->rchild) inorder_with_recursion(root->rchild);
}
后序(递归)
void postorder_with_recursion(NODE *root) {
if (root->lchild) postorder_with_recursion(root->lchild);
printf("%c", root->data);
if (root->rchild) postorder_with_recursion(root->rchild);
}
后序(非递归,用栈实现)
*方法转自站内其他博客
取巧方法,在前序遍历的非递归操作上作修改。
∵前序的非递归是左→中→右,而后序是左→右→中
∴在执行入栈操作时,左孩子先入栈,右孩子后入栈,将出栈顺序记录在数组中,并倒序输出即得到后序遍历序列
char reversed_postorder[MAXN]; //记录后序遍历倒序的数组
void postorder_without_recursion(NODE *root) {
NODE *stack[MAXN];
int top, i = 0;
if (t == NULL) return ;
stack[0] = root;
top = 1; //top指向下次入栈的位置
while (top > 0) {
root = stack[--top];
reversed_postorder[i++] = root->data; //将原本的输出操作换为将该结点值存入数组
//printf("%c", t->data);
if (root->lchild) stack[top++] = root->lchild;
if (root->rchild) stack[top++] = root->rchild;
}
}
层次遍历(用队列实现)
void levorder(NODE *root) {
NODE *queue[3 * MAXN], *p;
int head, tail, i;
queue[0] = root;
head = 0;
tail = 1; //下次入队结点下标
while (head < tail) {
p = queue[head++]; //队首结点出队
printf("%c", p->data);
if (p->lchild != NULL) q[tail++] = p->lchild; //左孩子入队
if (p->rchild != NULL) q[tail++] = p->rchild; //右孩子入队
}
}