C丨二叉树的遍历丨前序、中序、后序的递归和非递归实现+层次遍历

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; //右孩子入队
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值