-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path94-BinaryTreeInorderTraversal.kt
47 lines (40 loc) · 1.12 KB
/
94-BinaryTreeInorderTraversal.kt
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
43
44
45
46
47
/**
*
* Iterative Binary Tree Inorder Traversal
* https://leetcode.com/problems/binary-tree-inorder- traversal/submissions/
*
*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
import java.util.*
class Solution {
fun inorderTraversal(root: TreeNode?): List<Int> {
if (root == null){
return emptyList()
}
val resultList = mutableListOf<Int>()
val stack = LinkedList<TreeNode>()
stack.push(root!!)
while(stack.peek().left != null) {
stack.push(stack.peek().left)
}
while(stack.peek() != null) {
val node = stack.pop()
resultList.add(node.`val`)
if (node.right != null) {
stack.push(node.right!!)
while(stack.peek().left != null) {
stack.push(stack.peek().left)
}
}
}
return resultList
}
}