三种遍历的非递归实现

    // 非递归前序遍历
    public void preOrderTraversal() {
        preOrder1(root);
    }

    private void preOrderTraversal(Node x) {
        LinkedList<Node> list = new LinkedList<>();
        while (x != null || !list.isEmpty()) {
            while (x != null) {
                System.out.print("[" + x.key + ":" + x.value + "]" + " ");
                list.addFirst(x);
                x = x.lchild;
            }
            if (!list.isEmpty()) {
                x = list.removeFirst();
                x = x.rchild;
            }
        }
    }

    // 中序遍历:左子树--根节点--右子树
    public void inorderTraversal() {
        inorderTraversal(root);
    }
    private void inorderTraversal(Node x) {
        LinkedList<Node> stack = new LinkedList<>();
        while (x != null || !stack.isEmpty()) {
            while (x != null) {
                stack.addFirst(x);
                x = x.lchild;
            }
            Node node = stack.removeFirst();
            System.out.print("[" + node.key + ":" + node.value + "]" + " ");
            x = node.rchild;
        }
    }

    // 后续遍历思想: 左-右-根;可以视为, 根-右-左,然后结果转置即可.
    public void postOrderTraversal() {
        postOrderTraversal(root);
    }
    private void postOrderTraversal(Node x) {
        LinkedList<Node> stack = new LinkedList<>();
        LinkedList<Node> list = new LinkedList<>();
        stack.addFirst(x);
        while (!stack.isEmpty()) {
            Node node = stack.removeFirst();
            list.add(node);
            if (node.lchild != null)
                stack.push(node.lchild);
            if (node.rchild != null)
                stack.push(node.rchild);
        }
        Collections.reverse(list);
        for (Node node : list) {
            System.out.print("[" + node.key + ":" + node.value + "]" + " ");
        }
    }

借鉴文章:https://my.oschina.net/husthang/blog/852982

posted @ 2019-04-27 17:53  DongTian  阅读(253)  评论(0编辑  收藏  举报