|
2 | 2 |
|
3 | 3 | import java.util.*;
|
4 | 4 |
|
| 5 | + |
5 | 6 | // https://leetcode.com/problems/binary-tree-postorder-traversal/
|
6 | 7 | // 二叉树的后序遍历
|
7 | 8 | // 笔记:https://www.cnblogs.com/greyzeng/articles/15941957.html
|
@@ -54,37 +55,31 @@ public List<Integer> postorderTraversal2(TreeNode root) {
|
54 | 55 |
|
55 | 56 | // TODO
|
56 | 57 | // 【非递归】【单栈】后序遍历
|
57 | | - public static List<Integer> postorderTraversal1(TreeNode root) { |
58 | | - List<Integer> result = new ArrayList<>(); |
59 | | - if (root == null) { |
60 | | - return result; |
61 | | - } |
62 | | - |
63 | | - Stack<TreeNode> stack = new Stack<>(); |
64 | | - TreeNode current = root; // 当前探索指针 |
65 | | - TreeNode lastVisit = null; // 记录上一个被访问的节点 |
66 | | - |
67 | | - while (current != null || !stack.isEmpty()) { |
68 | | - // 1. 左链入栈:一直向左走,把所有左孩子压栈 |
69 | | - while (current != null) { |
70 | | - stack.push(current); |
71 | | - current = current.left; |
72 | | - } |
73 | | - |
74 | | - // 2. 查看栈顶节点(不弹出,先判断右子树) |
75 | | - TreeNode peekNode = stack.peek(); |
76 | | - |
77 | | - // 3. 如果右子树存在且未被访问过,则转向右子树 |
78 | | - if (peekNode.right != null && peekNode.right != lastVisit) { |
79 | | - current = peekNode.right; // 处理右子树 |
80 | | - } // 4. 否则(右子树为空或已访问),可以访问当前节点 |
81 | | - else { |
82 | | - result.add(peekNode.val); // 访问节点 |
83 | | - lastVisit = stack.pop(); // 记录已访问 |
84 | | - } |
85 | | - } |
86 | | - return result; |
87 | | - } |
| 58 | + public static List<Integer> postorderTraversal1(TreeNode h) { |
| 59 | + List<Integer> ans = new ArrayList<>(); |
| 60 | + if (h != null) { |
| 61 | + Stack<TreeNode> stack = new Stack<>(); |
| 62 | + stack.push(h); |
| 63 | + // 如果始终没有打印过节点,h就一直是头节点 |
| 64 | + // 一旦打印过节点,h就变成打印节点 |
| 65 | + // 之后h的含义 : 上一次打印的节点 |
| 66 | + while (!stack.isEmpty()) { |
| 67 | + TreeNode cur = stack.peek(); |
| 68 | + if (cur.left != null && h != cur.left && h != cur.right) { |
| 69 | + // 有左树且左树没处理过 |
| 70 | + stack.push(cur.left); |
| 71 | + } else if (cur.right != null && h != cur.right) { |
| 72 | + // 有右树且右树没处理过 |
| 73 | + stack.push(cur.right); |
| 74 | + } else { |
| 75 | + // 左树、右树 没有 或者 都处理过了 |
| 76 | + ans.add(cur.val); |
| 77 | + h = stack.pop(); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + return ans; |
| 82 | + } |
88 | 83 |
|
89 | 84 | // morris遍历实现后序遍历
|
90 | 85 | // 处理时机放在能回到自己两次的点,且第二次回到自己的时刻,第二次回到他自己的时候,
|
|
0 commit comments