Skip to content

Instantly share code, notes, and snippets.

@vamsitallapudi
Last active December 23, 2020 01:43
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/0242cc73c62a08282aec5bc8c947e390 to your computer and use it in GitHub Desktop.
Save vamsitallapudi/0242cc73c62a08282aec5bc8c947e390 to your computer and use it in GitHub Desktop.
import java.util.ArrayDeque
fun preOrderTraversalIterative(root: TreeNode?): List<Int> {
val myList = mutableListOf<Int>()
// creating stack to store the left and right nodes while processing root node
val stack = ArrayDeque<TreeNode>()
// checking edge case and returning empty list
if (root == null) return myList
var node = root
while (node != null || stack.isNotEmpty()) {
if (node != null) {
stack.push(node) // pushing before processing children
myList.add(node.data) //adding before going to left subtree
node = node.left
} else {
val p = stack.pop() // now popping stack to traverse right subtree
node = p.right
}
}
return myList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment