码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Binary Tree Preorder Traversal

时间:2016-02-21 18:25:22      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

lintcode-easy-Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5205302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!