> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/my-algorithm-summary/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/my-algorithm-summary/data-structure/tree/144-binary-tree-preorder-traversal.md).

# 144 Binary Tree Preorder Traversal

## 144. Binary Tree Preorder Traversal

## 1. Question

Given a binary tree, return thepreordertraversal of its nodes' values.

For example:\
Given binary tree`{1,#,2,3}`,

```
   1
    \
     2
    /
   3
```

return`[1,2,3]`.

## 2. Implementation

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode curNode = null;

        while (!stack.isEmpty()) {
            curNode = stack.pop();
            res.add(curNode.val);

            if (curNode.right != null) {
                stack.push(curNode.right);
            }

            if (curNode.left != null) {
                stack.push(curNode.left);
            }
        }
        return res;
    }
}
```

## 3. Time & Space Complexity

时间和空间复杂度都是O(n)
