---
# System prepended metadata

title: 'Binary Tree Inorder Traversal <img src="https://img.shields.io/badge/-easy-brightgreen">'
tags: [data_structure_python]

---

---
tags: data_structure_python
---

# Binary Tree Inorder Traversal <img src="https://img.shields.io/badge/-easy-brightgreen">

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

**Example:**

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

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

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


## Solution

### Solution 1: Recursive

```python=
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
        
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        
        def dfs(root, res):
            if root != None:
                dfs(root.left, res)
                res.append(root.val) # Inorder.
                dfs(root.right, res) 
        res = []
        dfs(root, res)
        return res
```

### Solution 2: Iterative

```python=
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        res, stack = [], [(root, False)]
        while len(stack) > 0:
            node, visited = stack.pop()  
            if node != None:
                if visited:
                    res.append(node.val)
                else: 
                    # stack.append((node, True)) # Postorder.
                    stack.append((node.right, False))
                    stack.append((node, True)) # Inorder.
                    stack.append((node.left, False))
                    # stack.append((node, True)) # Preorder.
        return res    
```