Skip to content

Instantly share code, notes, and snippets.

@vamsitallapudi
Last active December 23, 2020 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vamsitallapudi/38fb350df9c4d1d8c7ef505503f29a22 to your computer and use it in GitHub Desktop.
Save vamsitallapudi/38fb350df9c4d1d8c7ef505503f29a22 to your computer and use it in GitHub Desktop.
import java.util.ArrayDeque
fun inorderTraversalIterative(root: TreeNode?): List<Int> {
val list = mutableListOf<Int>()
if (root == null) return list
var node = root
val stack = ArrayDeque<TreeNode>()
// traversing the tree whenever right node is not null or the stack contains items
while (node != null || stack.isNotEmpty()) {
// processing all the left nodes of the current node
if (node != null) {
stack.push(node)
node = node.left //traversing to left node without processing root data
} else {
node = stack.pop()
list.add(node.data) // adding to the list if no left child
node = node.right // processing the right subtree
}
}
return list
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment