Last active
December 23, 2020 01:43
-
-
Save vamsitallapudi/0242cc73c62a08282aec5bc8c947e390 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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