# 144. Binary Tree Preorder Traversal

[Link](https://leetcode.com/problems/binary-tree-preorder-traversal/)

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

**Example:**

```
Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]
```

**Follow up:** Recursive solution is trivial, could you do it iteratively?

**Solution**

Idea: 透過stack紀錄那些node要先處理，先處理的後面insert。根據stack First in last out的原則。

```
 public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        if(root == null)
            return ret;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode targetNode = stack.pop();
            ret.add(targetNode.val);
            TreeNode rnode = targetNode.right;
            if(rnode != null){
                stack.push(rnode);
            }
            TreeNode lnode = targetNode.left;
            if(lnode != null){
                stack.push(lnode);
            }
        }
        return ret;
    }
```
