Binary Tree Preorder Traversal

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

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].

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

其实这个问题和postorder是一样的用自己的stack来代替recursion的stack,但是preorder不需要再用一个visited的hashSet来保存已经访问过的,因为当你pop一个treenode出来的时候,他的parent肯定已经被pop出来了,不存在又会将这个treenode放进stack重复计算的问题。代码如下

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        Stack<TreeNode> s = new Stack<TreeNode>();
        //HashSet<TreeNode> visited = new HashSet<TreeNode>();
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (root == null)
            return result;
        s.push(root);
        while(!s.isEmpty()) {
            TreeNode curr = s.pop(); // get mid
            //visited.add(curr);
            if (curr.right != null)
                s.push(curr.right);
            if (curr.left != null)
                s.add(curr.left);
            result.add(curr.val);
        }
        return result;
    }
}

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s