Last active
December 23, 2020 01:48
-
-
Save vamsitallapudi/38fb350df9c4d1d8c7ef505503f29a22 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 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