forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePostorderTraversal.java
More file actions
62 lines (52 loc) · 1.57 KB
/
BinaryTreePostorderTraversal.java
File metadata and controls
62 lines (52 loc) · 1.57 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package tree;
import java.util.*;
/**
* Created by gouthamvidyapradhan on 28/07/2018.
* Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
Solution: O(N). Maintain a stack, for every node which you pop from stack add it to result list, push left
and right node to stack. Reverse the result list and return this as the answer.
*/
public class BinaryTreePostorderTraversal {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static void main(String[] args) throws Exception{
TreeNode root = new TreeNode(1);
root.right = new TreeNode(2);
root.right.left = new TreeNode(3);
List<Integer> result = new BinaryTreePostorderTraversal().postorderTraversal(root);
result.forEach(System.out::println);
}
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
if(root != null){
stack.push(root);
}
while(!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if(node.left != null){
stack.push(node.left);
} if(node.right != null){
stack.push(node.right);
}
}
Collections.reverse(result);
return result;
}
}