-
Notifications
You must be signed in to change notification settings - Fork 15
/
binary-tree-postorder-traversal.java
44 lines (41 loc) · 1.16 KB
/
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
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in ArrayList which contains node values.
*/
public ArrayList<Integer> postorderTraversal(TreeNode root) {
// write your code here
ArrayList<Integer> list = new ArrayList<Integer>();
if (root == null) {
return list;
}
Stack<TreeNode> st = new Stack<TreeNode>();
st.push(root);
while (!st.isEmpty()) {
TreeNode node = st.pop();
list.add(node.val);
if (node.left != null) {
st.push(node.left);
}
if (node.right != null) {
st.push(node.right);
}
}
ArrayList<Integer> post = new ArrayList<Integer>();
for (int i = list.size() - 1; i >= 0; i--) {
post.add(list.get(i));
}
return post;
}
}