-
Notifications
You must be signed in to change notification settings - Fork 2
/
Solution.java
38 lines (33 loc) · 966 Bytes
/
Solution.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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> postorder = new ArrayList<Integer>();
TreeNode node;
if(root != null)
stack.push(root);
while(!stack.isEmpty()) {
node = stack.pop();
if(node.left == null && node.right == null) {
postorder.add(node.val);
} else {
stack.push(node);
if(node.right != null)
stack.push(node.right);
if(node.left != null)
stack.push(node.left);
node.left = null;
node.right = null;
}
}
return postorder;
}
}