Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e58db7d

Browse files
committed
binary tree post order traversal
1 parent 2e98d3c commit e58db7d

File tree

1 file changed

+26
-31
lines changed

1 file changed

+26
-31
lines changed

‎src/main/java/grey/algorithm/Code_0012_LeetCode_0145_BinaryTreePostorderTraversal.java

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.*;
44

5+
56
// https://leetcode.com/problems/binary-tree-postorder-traversal/
67
// 二叉树的后序遍历
78
// 笔记:https://www.cnblogs.com/greyzeng/articles/15941957.html
@@ -54,37 +55,31 @@ public List<Integer> postorderTraversal2(TreeNode root) {
5455

5556
// TODO
5657
// 【非递归】【单栈】后序遍历
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+
}
8883

8984
// morris遍历实现后序遍历
9085
// 处理时机放在能回到自己两次的点,且第二次回到自己的时刻,第二次回到他自己的时候,

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /