[LintCode/LeetCode] Binary Tree Preorder Traversal

518 查看

Problem

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?

Note

当你被challenge的时候,人家问,Can you do it without recursion? 一定要说,当然可以啦!所以,不用recursion,怎么办?幸好,这是一道preorder的题目,只要逐层遍历,就可以了。所以,试一试用堆栈的做法吧!记得Stack的特点是后入先出哦!

Solution

Recursion

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

Stack

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