二叉树的遍历(非递归)

二叉树的遍历(非递归)

本文分为以下部分:

上次文章中写的是递归版的二叉树遍历,这次采用非递归模式遍历二叉树。

前期准备

建立一个节点类,各个节点即可组成树

public class TreeNode {

    private int val;
    private TreeNode left;
    private TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }
}

构建树

1

@Test
public void test(){
    TreeNode root = new TreeNode(1);
    TreeNode node2 = new TreeNode(2);
    TreeNode node3 = new TreeNode(3);
    TreeNode node4 = new TreeNode(4);
    TreeNode node5 = new TreeNode(5);
    TreeNode node6 = new TreeNode(6);
    TreeNode node7 = new TreeNode(7);
    root.setLeft(node2);
    root.setRight(node3);
    node2.setLeft(node4);
    node2.setRight(node5);
    node3.setLeft(node6);
    node3.setRight(node7);
}

先序遍历

先序遍历为 先头,再左,最后右

准备一个栈 ,由于传入方法肯定就只有一个头节点,所以头节点入栈,弹出

  • 将弹出节点的右节点压入栈中
  • 左节点压入栈中
  • 弹出,重复步骤

2

private void preOrder(TreeNode root){
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()){
        TreeNode pop = stack.pop();
        System.out.print(pop.getVal() + " ");
        if(pop.getRight() != null){
            stack.push(pop.getRight());
        }
        if(pop.getLeft() != null){
            stack.push(pop.getLeft());
        }
    }
}

中序遍历

准备一个栈

  • 将左子树全部压入栈中
  • 弹出的时候输出,若存在右节点
  • 对右子树重复上面的操作

3

private void midOrder(TreeNode node){
    Stack<TreeNode> stack = new Stack<>();
    while (!stack.isEmpty() || node != null){
        if(node != null){
            stack.push(node);
            node = node.getLeft();
        }else{
            TreeNode pop = stack.pop();
            System.out.print(pop.getVal() + " ");
            node = pop.getRight();
        }
    }
}

后序遍历

后序遍历需要准备两个栈,一个辅助栈,一个输出栈

后序遍历为左右头,压入 stack2 中为 头右左,这样弹出来才符合后序遍历
在不考虑头的情况下(头也可以看成是左节点或者右节点)
从 stack1 从弹出的应该为 右左,这样压入 stack2 才是右左的顺序
则压入 stack1 的顺序为左右(与先序遍历相反)

3

private void  postOrder(TreeNode root){
    Stack<TreeNode> stack1 = new Stack<>();
    Stack<TreeNode> stack2 = new Stack<>();
    stack1.push(root);
    while (!stack1.isEmpty()){
        TreeNode pop = stack1.pop();
        stack2.push(pop);
        if(pop.getLeft() != null){
            stack1.push(pop.getLeft());
        }
        if(pop.getRight() != null){
            stack1.push(pop.getRight());
        }
    }

    while (!stack2.isEmpty()){
        TreeNode pop = stack2.pop();
        System.out.print(pop.getVal() + " ");
    }
}
posted @ 2021-12-20 10:05  抱糖果彡  阅读(41)  评论(0编辑  收藏  举报