---
description: >-
  https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
---

# 107. Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal 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]
]
```

## Thoughts

从下往上遍历二叉树。按层遍历并把结果倒过来。记录每层信息可以通过一个for循环保证只遍历Queue此层内元素。 倒序可以通过每次插在前面来完成。

## Code

```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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if not root: return []
        res, q = [], collections.deque()
        q.append(root)
        while len(q) > 0:
            r = [0] * len(q)
            for i in range(len(q)):
                t = q.popleft()
                r[i] = t.val
                if t.left: q.append(t.left)
                if t.right: q.append(t.right)
            res.insert(0, r)
        return res
        
```

```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<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> subres = new ArrayList<>();
            int length = queue.size();
            for (int i = 0; i < length; i++) {
                TreeNode node = queue.remove();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
                subres.add(node.val);
            }

            res.add(0, subres);
        }

        return res;
    }
}
```

## Analysis

时间复杂度为O(n).
