Binary Tree Preorder Traversal – Iterative way

Given a binary tree, return the preorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

Iterative Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList<int> PreorderTraversal(TreeNode root) {
        var list = new List<int>();
        Stack<TreeNode> s = new Stack<TreeNode>();
        TreeNode curNode = root;
        while(curNode != null || s.Count > 0)
        {
            while(curNode != null)
            {
                list.Add(curNode.val);
                s.Push(curNode);
                curNode = curNode.left;
            }
            
            if(s.Count > 0)
            {
                curNode = s.Pop();
                curNode = curNode.right;
            }
        }
        return list;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s