-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePostorderTraversal.java
More file actions
49 lines (47 loc) · 1.29 KB
/
Copy pathBinaryTreePostorderTraversal.java
File metadata and controls
49 lines (47 loc) · 1.29 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();//lifo
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
res.addFirst(cur.val);// 1.root 2. right->root 3. left-> right-> root.
if(cur.left!=null) stack.push(cur.left);
if(cur.right!=null) stack.push(cur.right);
}
return res;
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
helper(root, res);
return res;
}
private void helper(TreeNode root, List<Integer> res){
if(root == null) return;
helper(root.left, res);
helper(root.right, res);
res.add(root.val);
}
}
}