-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Postorder_Traversal.java
More file actions
48 lines (35 loc) · 1.12 KB
/
Binary_Tree_Postorder_Traversal.java
File metadata and controls
48 lines (35 loc) · 1.12 KB
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null) return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()){
TreeNode node = stack.peek();
if(node.left == null && node.right == null){
result.add(node.val);
stack.pop();
}
if(node.left != null){
stack.push(node.left);
node.left = null;
continue;
}
if(node.right != null){
stack.push(node.right);
node.right = null;
continue;
}
}
return result;
}
}