Skip to content

Commit

Permalink
create 94-Binary-Tree-Inorder-Traversal.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a committed Dec 28, 2022
1 parent da0dca2 commit 72ede76
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions kotlin/94-Binary-Tree-Inorder-Traversal.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//iterative version
class Solution {
fun inorderTraversal(root: TreeNode?): List<Int> {
val res = ArrayList<Int>()
val stack = Stack<TreeNode>()

var node = root
while(node != null || !stack.isEmpty()){
while(node != null){
stack.push(node)
node = node.left
}
node = stack.pop()
res.add(node.`val`)
node = node.right
}

return res
}
}

//recursion version
class Solution {
fun inorderTraversal(root: TreeNode?): List<Int> {
val res = ArrayList<Int>()

fun inOrder(node: TreeNode?) {
node?: return
inOrder(node.left)
res.add(node.`val`)
inOrder(node.right)
}

inOrder(root)
return res
}
}

0 comments on commit 72ede76

Please sign in to comment.