1. public class StackTree {
    2. static Node root;
    3. class Node {
    4. private int val;
    5. private Node rchild;
    6. private Node lchild;
    7. public Node(int val) {
    8. this.val = val;
    9. }
    10. }
    11. boolean insert(int val) {//添加树节点
    12. Node node = new Node(val);
    13. if (root == null) {
    14. root = node;
    15. return true;
    16. } else {
    17. Node cur = root;
    18. while (true) {
    19. Node newNode = new Node(val);
    20. if (cur.val > val) {
    21. if (cur.lchild == null) {
    22. cur.lchild = newNode;
    23. return true;
    24. }
    25. cur = cur.lchild;
    26. } else if (cur.val < val) {
    27. if (cur.rchild == null) {
    28. cur.rchild = newNode;
    29. return true;
    30. }
    31. cur = cur.rchild;
    32. } else {
    33. return false;
    34. }
    35. }
    36. }
    37. }
    38. /**
    39. * 先序
    40. * @param node
    41. */
    42. static void preorder(Node root) {
    43. if (root == null)
    44. return;
    45. Stack<Node> stack = new Stack<>();
    46. Node cur = root;
    47. while (cur != null || !stack.isEmpty()) {
    48. while (cur != null) {
    49. System.out.print(cur.val);//输出根
    50. stack.push(cur);//进栈
    51. cur = cur.lchild;//遍历左子树
    52. }
    53. cur = stack.pop();
    54. cur = cur.rchild;
    55. }
    56. }
    57. /**
    58. * 中序
    59. * @param node
    60. */
    61. static void inorder(Node root) {
    62. if (root == null)
    63. return;
    64. Stack<Node> stack = new Stack<StackTree.Node>();
    65. Node cur = root;
    66. while (cur != null || !stack.isEmpty()) {
    67. while (cur != null) {
    68. stack.push(cur);
    69. cur = cur.lchild;
    70. }
    71. cur = stack.pop();
    72. System.out.println(cur.val);
    73. cur = cur.rchild;
    74. }
    75. }
    76. /**
    77. * 后序,双栈法
    78. * @param node
    79. */
    80. static void postorder1(Node root) {
    81. if(root == null) return ;
    82. Stack<Node> stack = new Stack<StackTree.Node>();
    83. Stack<Node> stack1 = new Stack<StackTree.Node>();
    84. Node cur = root;
    85. while(cur != null || !stack.isEmpty()) {
    86. while(cur!=null) {
    87. stack1.push(cur);
    88. stack.push(cur);
    89. cur = cur.rchild;
    90. }
    91. cur = stack.pop();
    92. cur = cur.lchild;
    93. }
    94. int n = stack1.size();
    95. for (int i = 0; i < n; i++) {
    96. System.out.print(stack1.pop().val);
    97. }
    98. }
    99. /**
    100. * 后序,单栈标记法
    101. * @param node
    102. */
    103. static void postorder(Node node) {
    104. if (root == null)
    105. return;
    106. Stack<Node> stack = new Stack<StackTree.Node>();
    107. Node cur = root;
    108. Node t = null;//标识是否已经出栈
    109. while (cur != null || !stack.isEmpty()) {
    110. while (cur != null) {
    111. stack.push(cur);
    112. cur = cur.lchild;
    113. }//cur.left == null
    114. cur = stack.peek();//取栈顶元素
    115. if(cur.rchild == null || t == cur.rchild) {//右子树为空或者右子树已经处理过
    116. t = stack.pop();//出栈,标识是否已经处理过
    117. System.out.print(t.val);
    118. cur = null;
    119. }else {
    120. cur = cur.rchild;
    121. }
    122. }
    123. }
    124. static void preOrder(Node node) {
    125. if (node == null)
    126. return;
    127. System.out.print(node.val);
    128. preOrder(node.lchild);
    129. preOrder(node.rchild);
    130. }
    131. static void inOrder(Node node) {
    132. if (node == null)
    133. return;
    134. inOrder(node.lchild);
    135. System.out.print(node.val);
    136. inOrder(node.rchild);
    137. }
    138. static void postOrder(Node node) {
    139. if (node == null)
    140. return;
    141. postOrder(node.lchild);
    142. postOrder(node.rchild);
    143. System.out.print(node.val);
    144. }
    145. public static void main(String[] args) {
    146. StackTree tree = new StackTree();
    147. int[] a = { 2, 5, 1, 3, 9, 8, 7, 4, 6 };
    148. for (int i = 0; i < a.length; i++) {
    149. tree.insert(a[i]);
    150. }
    151. preOrder(root);
    152. System.out.println();
    153. preorder(root);
    154. System.out.println();
    155. inOrder(root);
    156. System.out.println();
    157. inorder(root);
    158. postOrder(root);
    159. System.out.println();
    160. postorder(root);
    161. System.out.println();
    162. postorder1(root);
    163. }
    164. }

    用栈的方式(非递归)来实现二叉树的遍历,说白了只是拿我们的用户定义栈去替换系统栈而已,其它并没有本质的区别,来看个例子就知道了。

    二叉树前序遍历的递归写法

    public void preorder(Node root) {
        if (root != null) {
            System.out.println(root.val);
            preorder(root.left);
            preorder(root.right);
        }
    }
    

    二叉树前序遍历的非递归写法

    public void preorder(Node root) {
        if (root == null)
            return;
        Stack<Node> stack = new Stack<>();
        Node cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                System.out.print(cur.val);//输出根
                stack.push(cur);//进栈
                cur = cur.lchild;//遍历左子树
            }
            cur = stack.pop();
            cur = cur.rchild;
        }
    }
    

    可以看出来,递归和非递归都是先把当前 root 的值打印出来,然后不停地去遍历左子树,直到左子树为空。

    // 递归
    preorder(root.left);
    
    // 非递归
    stack.push(cur);//进栈
    cur = cur.lchild;//遍历左子树
    

    然后判断当前结点的左子树为空后,开始遍历它的右子树

    // 递归
    preorder(root.right);
    
    // 非递归
    while (...) {
        ...
    }
    cur = stack.pop();
    cur = cur.rchild;
    

    中序遍历也是如此:

    二叉树中序遍历的递归写法

    public void inorder(Node root) {
        if (root != null) {
            inorder(root.left);
            System.out.println(root.val);
            inorder(root.right);
        }
    }
    

    二叉树中序遍历的非递归写法

    public void inorder(Node root) {
        if (root == null)
            return;
        Stack<Node> stack = new Stack<>();
        Node cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            System.out.println(cur.val);
            cur = cur.right;
        }
    }
    

    后序遍历有些特殊,先来看看后序遍历的递归写法:

    后序遍历的递归写法:

    public void postorder(Node root) {
        if (root != null) {
            postorder(root.left);
            postorder(root.right);
            System.out.println(root.val);
        }
    }
    

    因为访问/输出 结点值是最后才执行的,所以无法边遍历边访问,只能把结点值放到一个栈中最后才访问。

    而由于栈是先进后出的,所以我们得逆序保存结点

    后序遍历的非递归写法:

    public void postorder(Node root) {
        if (root == null) return;
        Stack<Node> stack1 = new Stack<>();
        Stack<Node> stack2 = new Stack<>();
        Node cur = root;
        while (cur != null || !stack1.isEmpty()) {
            while (cur != null) {
                // 根节点是最后访问的,先入栈的后访问
                stack1.push(cur);
                stack2.push(cur);
                cur = cur.right;
            }
            cur = stack.pop();
            cur = cur.left;
        }
        // 访问结点
        int n = stack2.size();
        for (int i = 0; i < n; i++) {
            System.out.print(stack2.pop().val);
        }    
    }
    

    但是上面这种写法需要完整遍历一遍树后,才能开始访问树的每一个节点,如果想一边遍历一边访问的话,就需要和递归写法靠近了。

    public void postorder(Node root) {
        if (root == null)
            return;
        Stack<Node> stack = new Stack<StackTree.Node>();
        Node cur = root;
        Node t = null; //标识是否已经出栈
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.lchild;
            } //cur.left == null
            cur = stack.peek(); //取栈顶元素
            if(cur.rchild == null || t == cur.rchild) { //右子树为空或者右子树已经处理过
                t = stack.pop(); //出栈,标识是否已经处理过
                System.out.print(t.val);
                cur = null;
            }else {
                cur = cur.rchild;
            }
        }
    }
    

    其中 t == cur.rchild 很重要,不能在 if 里面只判断 if(cur.rchild == null) ,因为当前结点的右孩子遍历完后,就开始遍历当前结点了,如果只有if(cur.rchild == null),那么又会进入到 else 分支去执行 cur = cur.rchild 造成无限循环,因此需要做标记才行(手动添加 visited Set 也可以,不过会浪费一定空间)