# Does anyone have an iterative accepted solution?

• Below is the straight forward recursive solution, does any one have the iterative implementation for the same?

``````public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer>list = new ArrayList<Integer>();
return recursion(root, list);
}
public List<Integer> recursion(TreeNode root, List<Integer> list){
if(root!=null){
recursion(root.left,list);
recursion(root.right,list);
}else{
return list;
}

return list;
}
}``````

• Simply, using recursion means that you are using call stack and your mutable state and order of execution are kept there. So if you should not use recursion, in other words, call stack -- get your own stack. You need to push items to the stack in such a way that when popped out the order will be correct. Thus I push right branch before left.

``````public class Solution
{
public List<Integer> preorderTraversal(TreeNode root)
{
Stack<TreeNode> stack = new Stack<>();

// start with the root of the tree even if it is null
stack.push(root);

while (!stack.empty())
{
TreeNode n = stack.pop();
if (n != null)
{
stack.push(n.right);
stack.push(n.left);
}
}

return integers;

}
}
``````

• Thanks...nice solution.

• Stay on this track and may the force be with you! :)

• Here is my solution.

``````public List<Integer> preorderTraversal(TreeNode root) {
for (Stack<TreeNode> toVisit = new Stack<>(); root != null; root = root.left != null ? root.left : toVisit.isEmpty() ?  null : toVisit.pop()) {
if (root.right != null) toVisit.push(root.right);
}
return res;
}
``````

It's a bit silly and definitely abuses the spirit of a for loop, but otherwise, it simply uses a Stack like every other iterative solution. Perhaps the only noteworthy aspect is that this avoids pushing the left nodes onto the stack since, if a left node exists, we can just go to it directly.

• very smart.........simple

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.