Wednesday, March 4, 2015

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?
Solution: iterator
用一个stack来模拟递归的过程。所以算法时间复杂度是O(n),空间复杂度是栈的大小O(logn)
http://blog.csdn.net/linhuanmars/article/details/21428647
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList preorderTraversal(TreeNode root) {
        ArrayList res = new ArrayList();
        LinkedList stack = new LinkedList();
        
        if(root == null)
            return res;
            
        while(!stack.isEmpty() || root != null) {
            if(root != null) {
                stack.push(root);
                res.add(root.val);
                root = root.left;
            }else {
                TreeNode temp = stack.pop();
                root = temp.right;
            }
        }
        return res;
    }
}
Or
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List preorderTraversal(TreeNode root) {
        List result = new ArrayList();

        if(root == null) 
            return result;
        
        Stack stack = new Stack();
        stack.push(root);
        
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            result.add(node.val);
            
            if(node.right != null)
                stack.push(node.right);
            
            if(node.left != null)
                stack.push(node.left);
        }
        return result;
    }
}

No comments:

Post a Comment