Skip to content

Commit c9ebdad

Browse files
authored
Create 0144-binary-tree-preorder-traversal.kt
1 parent 2d54b27 commit c9ebdad

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//iterative version
2+
class Solution {
3+
fun preorderTraversal(root: TreeNode?): List<Int> {
4+
val res = ArrayList<Int>()
5+
val stack = Stack<TreeNode>()
6+
7+
if (root != null) stack.push(root)
8+
9+
while (!stack.isEmpty()) {
10+
11+
val node = stack.pop()
12+
res.add(node.`val`)
13+
14+
if (node.right != null) stack.push(node.right)
15+
if (node.left != null) stack.push(node.left)
16+
}
17+
18+
return res
19+
}
20+
}
21+
22+
//recursion version
23+
class Solution {
24+
fun preorderTraversal(root: TreeNode?): List<Int> {
25+
val res = ArrayList<Int>()
26+
27+
fun preOrder(node: TreeNode?) {
28+
node?: return
29+
res.add(node.`val`)
30+
preOrder(node.left)
31+
preOrder(node.right)
32+
}
33+
34+
preOrder(root)
35+
return res
36+
}
37+
}

0 commit comments

Comments
 (0)