-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinaryTreePostorderTraversal.java
46 lines (43 loc) · 1.23 KB
/
BinaryTreePostorderTraversal.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
package leetcode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
/**
* Created by Edward on 28/07/2017.
*/
public class BinaryTreePostorderTraversal {
/**
* 145. Binary Tree Postorder Traversal
*
* time : O(n);
* space : O(n);
* @param root
* @return
*/
public static List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
helper(res, root);
return res;
}
public static void helper(List<Integer> res, TreeNode root) {
if (root == null) return;
helper(res, root.left);
helper(res, root.right);
res.add(root.val);
}
public static List<Integer> postorderTraversal2(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
res.addFirst(cur.val);
if (cur.left != null) stack.push(cur.left);
if (cur.right != null) stack.push(cur.right);
}
return res;
}
}