-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePreorderTraversal.java
More file actions
42 lines (36 loc) · 1.09 KB
/
BinaryTreePreorderTraversal.java
File metadata and controls
42 lines (36 loc) · 1.09 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
package leetcode;
import utils.TreeNode;
import utils.Trees;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
/**
* BinaryTreePreorderTraversal
* https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
*
* @since 2020-10-27
*/
public class BinaryTreePreorderTraversal {
public static void main(String[] args) {
TreeNode head = Trees.fromIntegers(new Integer[]{1, null, 2, 3});
BinaryTreePreorderTraversal sol = new BinaryTreePreorderTraversal();
List<Integer> res = sol.preorderTraversal(head);
for (Integer value : res) {
System.out.println(value);
}
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode head = stack.pop();
if (head != null) {
res.add(head.val);
stack.add(head.right);
stack.add(head.left);
}
}
return res;
}
}