Skip to content

Commit bfc469a

Browse files
committed
add solution of problem 144: binary tree preorder traversal
1 parent 4bed5e7 commit bfc469a

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Given a binary tree, return the *preorder* traversal of its nodes' values.
2+
3+
For example:
4+
5+
Given binary tree `{1,#,2,3}`,
6+
```
7+
1
8+
\
9+
2
10+
/
11+
3
12+
```
13+
return `[1,2,3]`.
14+
15+
**Note:** Recursive solution is trivial, could you do it iteratively?
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
public List<Integer> preorderTraversal(TreeNode root) {
12+
List<Integer> result = new ArrayList<Integer>();
13+
14+
if (root != null)
15+
preorderTraversal(root, result);
16+
17+
return result;
18+
}
19+
20+
private void preorderTraversal(TreeNode node, List<Integer> result) {
21+
result.add(node.val);
22+
if (node.left != null)
23+
preorderTraversal(node.left, result);
24+
25+
if (node.right != null)
26+
preorderTraversal(node.right, result);
27+
}
28+
}

0 commit comments

Comments
 (0)