---
# System prepended metadata

title: 0094. Binary Tree Inorder Traversal
tags: [Leetcode, Easy, Tree Traversal]

---

# 0094. Binary Tree Inorder Traversal
###### tags: `Leetcode` `Easy` `Tree Traversal`
Link: https://leetcode.com/problems/binary-tree-inorder-traversal/

[参考](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/er-cha-shu-de-zhong-xu-bian-li-by-leetcode-solutio/)
## Code
### Recursion
```java=
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> l = new ArrayList<>();
        inOrderBST(root, l);
        return l;
    }
    public void inOrderBST(TreeNode root, List<Integer> l){
        if(root == null) return;
        inOrderBST(root.left,l);
        l.add(root.val);
        inOrderBST(root.right,l);
        return;
    }
}
```
### 非递归 - 颜色标记法
核心思想：
- 是用颜色标记节点的状态，新节点为白色，已访问的节点为灰色
- 如果遇到的节点为白色，则将其标记为灰色，然后按照遍历顺序将节点们依次入栈（是反过来的顺序，ex. 如果是中序遍历，则放的顺序是 右、自身、左）
- 如果遇到的节点是灰色的，则将节点的值输出
```java=
class Solution {
    class ColorNode{
        TreeNode node;
        Integer color;
        //0 -> new node
        //1 -> visited node
        
        public ColorNode(TreeNode node, Integer color){
            this.node = node;
            this.color = color;
        }
    }
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> l = new ArrayList<>();
        if(root == null) return l;
        Stack<ColorNode> stack = new Stack<>();
        stack.add(new ColorNode(root, 0));
        while(!stack.isEmpty()){
            ColorNode cnode = stack.pop();
            if(cnode.color == 0){
                if(cnode.node.right != null) stack.add(new ColorNode(cnode.node.right,0));
                stack.add(new ColorNode(cnode.node,1));
                if(cnode.node.left != null) stack.add(new ColorNode(cnode.node.left,0));
            }
            else{
                l.add(cnode.node.val);
            }
        }
        return l;
    }
}
```
### Morris 中序遍历 空间复杂度为O(1)
```java=
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> l = new ArrayList<>();
        TreeNode predecessor = null;
        
        while(root != null){
            if(root.left == null){
                l.add(root.val);
                root = root.right;
            }
            else{
                predecessor = root.left;
                while(predecessor.right!=null && predecessor.right!=root){
                    predecessor = predecessor.right;
                }
                if(predecessor.right==null){
                    predecessor.right = root;
                    root = root.left;
                }
                else{
                    l.add(root.val);
                    root = root.right;
                    predecessor.right = null;
                }
            }
        }
        return l;
    }
}
```