> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/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/algorithm-practice/leetcode/tree/107-binary-tree-level-order-traversal-ii.md).

# 107 Binary Tree Level Order Traversal II

## 107. Binary Tree Level Order Traversal II

## 1. Question

Given a binary tree, return thebottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:\
Given binary tree`[3,9,20,null,null,15,7]`,

```
    3
   / \
  9  20
    /  \
   15   7
```

return its bottom-up level order traversal as:

```
[
  [15,7],
  [9,20],
  [3]
]
```

## 2. Implementation

**(1) BFS**

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

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

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        List<Integer> level = null;

        while (!queue.isEmpty()) {
            int size = queue.size();
            level = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();
                level.add(curNode.val);

                if (curNode.left != null) {
                    queue.add(curNode.left);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            } 
            res.add(0, level);
        }
        return res;
    }
}
```

**(2) DFS**

```java
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        getLevelOrderByDFS(root, 0, res);
        return res;
    }

    public void getLevelOrderByDFS(TreeNode node, int depth, List<List<Integer>> res) {
        if (node == null) {
            return;
        }

        if (res.size() == depth) {
            res.add(0, new ArrayList<>());
        }
        res.get(res.size() - depth - 1).add(node.val);

        getLevelOrderByDFS(node.left, depth + 1, res);
        getLevelOrderByDFS(node.right, depth + 1, res);
    }
}
```

## 3. Time & Space Complexity

BFS: 时间复杂度: O(n), 空间复杂度: O(n)

DFS: 时间复杂度: O(n), 空间复杂度: O(n)
