forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_145.java
89 lines (83 loc) · 2.62 KB
/
_145.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class _145 {
public static class Solution1 {
/**
* A tricky/hacky one: Modify the code for pre-order traversal
* so that it becomes root->right->left,
* and then reverse the result to get left->right->root.
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
result.add(root.val);
if (root.left != null) {
stack.push(root.left);
}
if (root.right != null) {
stack.push(root.right);
}
}
Collections.reverse(result);
return result;
}
}
public static class Solution2 {
/**
* Or use a LinkedList and add values to the head, then no reverse is needed.
* the linked list contents get added like this:
* <p>
* root
* right, root
* left, right, root
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new LinkedList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode curr = stack.pop();
list.add(0, curr.val);
if (curr.left != null) {
stack.push(curr.left);
}
if (curr.right != null) {
stack.push(curr.right);
}
}
return list;
}
}
public static class Solution3 {
/**
* recursive solution is trivial.
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
return post(root, result);
}
List<Integer> post(TreeNode root, List<Integer> result) {
if (root == null) {
return result;
}
post(root.left, result);
post(root.right, result);
result.add(root.val);
return result;
}
}
}