lintcode-easy-Binary Tree Preorder Traversal

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

Example

Given:

    1
   / \
  2   3
 / \
4   5

return [1,2,4,5,3].

Challenge

Can you do it without recursion?

 

1. recursive

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        if(root == null)
            return result;
        
        helper(root, result);
        
        return result;
    }
    
    public void helper(TreeNode root, ArrayList<Integer> result){
        if(root == null)
            return;
        else{
            result.add(root.val);
            helper(root.left, result);
            helper(root.right, result);
            
            return;
        }
        
    }
    
}

2. iterative

方法和中序遍历差不多

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        if(root == null)
            return result;
        
        TreeNode p = null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        stack.push(root);
        
        while(p != null || !stack.isEmpty()){
            if(p != null){
                result.add(p.val);
                
                if(p.right != null){
                    stack.push(p.right);
                }
                p = p.left;
            }
            else{
                p = stack.pop();
            }
        }
        
        return result;
    }
}

 

posted @ 2016-02-21 17:56  哥布林工程师  阅读(191)  评论(0编辑  收藏  举报