[LeetCode 145] Binary Tree Postorder Traversal
LeetCode 145 (Java)
[Binary Tree Postorder Traversal] 문제 풀이
[LeetCode 145] Binary Tree Postorder Traversal
Description
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
Example 1
Example 2
Example 3
- Input: root = []
- Output: []
Example 4
- Input: root = [1]
- Output: [1]
Constraints
- The number of the nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<Integer> ans = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
dfs(root);
return ans;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
dfs(root.right);
ans.add(root.val);
}
}
| Runtime | Memory |
|---|---|
| 0 ms | 41.8 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
/*class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
postorder(root,res);
return res;
}
private void postorder(TreeNode root,List<Integer> res){
if(root==null){
return;
}
postorder(root.left,res);
postorder(root.right,res);
res.add(root.val);
}
}*/
class Solution{
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> ans = new ArrayList<>();
Stack<TreeNode> st = new Stack<>();
if(root==null){
return ans;
}
st.push(root);
while(!st.isEmpty()){
TreeNode s = st.pop();
ans.add(s.val);
if(s.left!=null){
st.push(s.left);
}
if(s.right!=null){
st.push(s.right);
}
}
Collections.reverse(ans);
return ans;
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/0100-0199/0145.Binary%20Tree%20Postorder%20Traversal/Solution.java
This post is licensed under CC BY 4.0 by the author.


