# 二叉树的前中后遍历

## 二叉树的前序遍历

```   1
\
2
/
3
```

```   1
/
2
```

### 递归

```class TreeTraversal {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
preorder(root, res);
return res;
}

public void preorder(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
preorder(root.left, res);
preorder(root.right, res);
}
}
```

### 非递归

```class TreeTraversal {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) {
return res;
}

Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;
}
return res;
}
}
```

## 二叉树的中序遍历

```   1
\
2
/
3
```

```   1
/
2
```

### 递归

```class TreeTraversal {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inorder(root, res);
return res;
}

public void inorder(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
inorder(root.left, res);
inorder(root.right, res);
}
}
```

### 非递归

```class TreeTraversal {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return res;
}
}
```

## 二叉树的后序遍历

```   1
\
2
/
3
```

### 递归

```class TreeTraversal {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
postorder(root, res);
return res;
}

public void postorder(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
postorder(root.left, res);
postorder(root.right, res);
}
}
```

### 非递归

```class TreeTraversal {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) {
return res;
}

Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode prev = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.right == null || root.right == prev) {
prev = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return res;
}
}
```