leetcode PreorderTravel
z
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
import utils.ListNode;
import utils.TreeNode;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class PreorderTravel {
/*
Input: [1,null,2,3]

1
\
2
/
3

Output: [1,2,3]
better not recurritive but iterative
*/
public static void main(String[] args){

}
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> s = new Stack<>();
List<Integer> ans = new LinkedList<>();

if (root != null){
s.push(root);
}
while(!s.isEmpty()) {
root = s.pop();
ans.add(root.val);
TreeNode left = root.left;
TreeNode right = root.right;
if (right != null) {
s.push(right);
}
if (left != null){
s.push(left);
}

}
return ans;



}
}