728x90
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> ans = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return ans;
}
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
ans.addFirst(cur.val);
if (cur.left != null) {
stack.push(cur.left);
}
if (cur.right != null) {
stack.push(cur.right);
}
}
return ans;
}
}
Postorder Traversal은
Left, Right, Visit 의 순서로 기억하면 된다.
728x90
'알고리즘' 카테고리의 다른 글
[프로그래머스] 가장 긴 팰린드롬 (0) | 2023.12.08 |
---|---|
[LeetCode] 501. Find Mode in Binary Search Tree (0) | 2023.12.06 |
[LeetCode] 144. Binary Tree Preorder Traversal (0) | 2023.12.05 |
[LeetCode] 94. Binary Tree Inorder Traversal (0) | 2023.12.05 |
[LeetCode] 111. Minimum Depth of Binary Tree (0) | 2023.12.05 |