-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBinaryTreePreorderTraversal.java
More file actions
34 lines (34 loc) · 1.01 KB
/
BinaryTreePreorderTraversal.java
File metadata and controls
34 lines (34 loc) · 1.01 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreePreorderTraversal {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
TreeNode current = root;
while (current != null) {
if (current.left == null) {
res.add(current.val);
current = current.right;
} else {
TreeNode prev = current.left;
while (prev.right != null && prev.right != current)
prev = prev.right;
if (prev.right == null) {
prev.right = current;
res.add(current.val);
current = current.left;
} else {
prev.right = null;
current = current.right;
}
}
}
return res;
}
}