forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0145-binary-tree-postorder-traversal.java
46 lines (41 loc) · 1.2 KB
/
0145-binary-tree-postorder-traversal.java
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
class Solution {
// Iterative
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
Stack<Boolean> visit = new Stack<>();
visit.add(false);
List<Integer> res = new ArrayList<>();
while(!stack.isEmpty()){
TreeNode curr=stack.pop();
boolean v = visit.pop();
if(curr != null){
if(v != false){
res.add(curr.val);
}else{
stack.add(curr);
visit.add(true);
stack.add(curr.right);
visit.add(false);
stack.add(curr.left);
visit.add(false);
}
}
}
return res;
}
}
class Solution {
// Recursive
public void postorder(TreeNode root, List<Integer> res){
if(root == null) return;
postorder(root.left, res);
postorder(root.right, res);
res.add(root.val);
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
postorder(root, res);
return res;
}
}