二叉树的遍历

先序遍历(DLR)Data-Lchild-Rchild

// 先序遍历(DLR)Data-Lchild-Rchild
public void PreOrder(BiTreeNode tree){
    if (tree != null){
        System.out.println(tree);
        PreOrder(tree.lchild);
        PreOrder(tree.rchild);
    }
}

中序遍历(LDR)Lchild-Data-Rchild

// 中序遍历(LDR)Lchild-Data-Rchild
public void InOrder(BiTreeNode tree){
    if (tree != null){
        InOrder(tree.lchild);
        System.out.println(tree);
        InOrder(tree.rchild);
    }
}

中序非递归遍历

// 中序遍历的非递归算法
public void InOrder(BiTreeNode tree) {
    LinkedList<BiTreeNode> stack = new LinkedList<>();  // 辅助栈
    BiTreeNode pointer = tree;    // 中序遍历的顺序指针
    while (!stack.isEmpty() || pointer != null) {
        if (pointer != null) {    // 顺序指针非空说明仍有左孩子
            stack.push(pointer);
            pointer = pointer.lchild;
        } else {    // 顺序指针已指向最左叶结点,出栈结点并访问,然后指向这个结点的右孩子
            BiTreeNode pop = stack.pop();
            System.out.println(pop);
            pointer = pop.rchild;
        }
    }
}

后序遍历(LRD)Lchild-Rchild-Data

// 后序遍历(LRD)Lchild-Rchild-Data
public void PostOrder(BiTreeNode tree){
    if (tree != null){
        PostOrder(tree.lchild);
        PostOrder(tree.rchild);
        System.out.println(tree);
    }
}

后序非递归遍历

LinkedList<BiTreeNode> stack = new LinkedList<>();    // 辅助栈,存放二叉树遍历的顺序
BiTreeNode pointer;    // 二叉树遍历的工作指针
BiTreeNode pre;    // 前驱结点,遍历右子树回溯时保存刚刚访问的右孩子
// 后序遍历(LRD)Lchild-Rchild-Data
public void PostOrder(BiTreeNode tree){
    LinkedList<BiTreeNode> stack = new LinkedList<>();
    BiTreeNode pointer = tree;
    BiTreeNode pre = null;
    
    while (pointer != null || !stack.isEmpty()) {
        if (pointer != null) {
            stack.push(pointer);
            pointer = pointer.lchild;
        }
        else if (!stack.isEmpty()) {
            pointer = stack.getFirst(); // 获取栈顶但不出栈
            if (pointer.rchild == null || pointer.rchild == pre) {  // 如果p指针的右孩子为null或者p指针的右孩子刚访问过
                System.out.println(pointer);
                stack.pop();
                pre = pointer;
                pointer = null; // 如果p指针不置零,下次循环会找到p指针最左孩子的位置
            } else {
                pointer = pointer.rchild;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值