二叉树实战(十):非递归方式遍历二叉树

二叉树遍历,使用递归方式是很简单的,也是很基础的实现方式。 那么不用递归的话,我们怎么实现呢?

【思路】:

如果不用递归遍历二叉树,那么我们肯定需要用到循环。如何保存节点信息呢? 答: 栈 !

辅助基础节点:

    public static class Node {
        Node left;
        Node right;
        int value;

        public Node(int value) {
            this.value = value;
        }
    }

前序遍历二叉树(非递归)

根节点 -> 左子树 -> 右子树

public static void preOrder(Node root) {
    Stack<Node> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        Node temp = stack.pop();
        if (temp != null) {
            System.out.print(temp.value + " ");
            if (temp.right != null) {
                stack.push(temp.right);
            }
            if (temp.left != null) {
                stack.push(temp.left);
            }
        }
    }
}

中序遍历二叉树(非递归)

public static void inOrder(Node root) {
    Stack<Node> stack = new Stack<Node>();
    stack.push(root);
    while (root.left != null) {
        stack.push(root.left);
        root = root.left;
    }
    while (!stack.isEmpty()) {
        Node temp = stack.pop();
        if (temp != null) {
            System.out.print(temp.value + " ");
            if (temp.right != null) {
                Node n1 = temp.right;
                stack.push(temp.right);
                while (n1.left != null) {
                    stack.push(n1.left);
                    n1 = n1.left;
                }
            }
        }
    }
}

后序遍历二叉树(非递归)

public static void postOrder(Node  root) {
    Stack<Node> stack = new Stack<>();
    Stack<Node> stackPop = new Stack<>();
    stack.push(root);
    while(!stack.isEmpty()) {
        Node node = stack.pop();
        if(node != null) {
            stackPop.push(node);
            if(node.left != null) {
                stack.push(node.left);
            }
            if(node.right != null) {
                stack.push(node.right);
            }
        }
    }
    while(!stackPop.isEmpty()) {
        System.out.print(stackPop.pop().value+ " ");
    }
}

推荐资料:

采用非递归方式遍历二叉树:https://www.cnblogs.com/moris5013/p/11652285.html

posted @ 2021-07-14 15:54  灰色飘零  阅读(93)  评论(0)    收藏  举报