145. Binary Tree Postorder Traversal - Easy
前往題目
想法
- 和
inorder
與preorder
差不多,調換加入的順序
思路
與inorder
還有preorder
有點區別,比較刁鑽
- 迭代整個樹
- 過程中只要當前節點不是
null
就加入答案,並且放入stack
,繼續往右邊節點走 - 當前節點為
null
時才去左邊節點 - 反轉答案並回傳
postorder
是先訪問左右子節點再訪問父節點,因此這個思路是反過來操作,所以在最後直接反轉就是答案
Code
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
Stack<TreeNode> stack = new Stack();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
// Go to the right child
if (cur != null) {
// Add before going to children, that's why reverse at the end
res.add(cur.val);
stack.push(cur);
cur = cur.right;
} else {
cur = stack.pop();
cur = cur.left;
}
}
Collections.reverse(res);
return res;
}
}
145. Binary Tree Postorder Traversal - Easy
https://f88083.github.io/2024/10/17/145-Binary-Tree-Postorder-Traversal-Easy/