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

144. Binary Tree Preorder Traversal

时间:2015-05-07 06:27:10      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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?

 

Hide Tags
 Tree Stack
 

连接: http://leetcode.com/problems/binary-tree-preorder-traversal/

题解:

二叉树先序遍历, root -> left -> right。使用一个栈来维护已经访问过的节点。当root不为空时,当前节点入栈,输出节点值,继续向左子树遍历。当root为空,从栈中弹出节点,向右子树进行遍历。

Iterative:

Time Complexity - O(n),  Space Complexity - O(n)。

public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null)
            return result;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        while(root != null || !stack.isEmpty()){
            if(root != null){
                stack.push(root);
                result.add(root.val);
                root = root.left;
            } else {
                root = stack.pop();
                root = root.right;
            }
        }
        
        return result;
    }
}

Recursive:

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null)
            return result;
        helper(result, root);
        return result;
    }
    
    private void helper(ArrayList<Integer> result, TreeNode root){
        if(root == null)
            return;
        result.add(root.val);
        helper(result, root.left);
        helper(result, root.right);
    }
}

 

 

Morris-Travel:

测试:

 

144. Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4483758.html

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