# [LeetCode] 107. Binary Tree Level Order Traversal II 二叉树层序遍历 II

2021年09月15日 阅读数：2

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).html

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

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

return its bottom-up level order traversal as:python

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

102. Binary Tree Level Order Traversal 的变形，只是最后输出的顺序变了，这题是从最后一层开始。app

Python：ide

```class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []

result, current = [], [root]
while current:
next_level, vals = [], []
for node in current:
vals.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current = next_level
result.append(vals)

return result[::-1]　```

C++：Iterationpost

```class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int> > res;
if (root == NULL) return res;

queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> oneLevel;
int size = q.size();
for (int i = 0; i < size; ++i) {
TreeNode *node = q.front();
q.pop();
oneLevel.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.insert(res.begin(), oneLevel);
}
return res;
}
};
```

C++：Recursionurl

```class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int> > res;
levelorder(root, 0, res);
return vector<vector<int> > (res.rbegin(), res.rend());
}
void levelorder(TreeNode *root, int level, vector<vector<int> > &res) {
if (!root) return;
if (res.size() == level) res.push_back({});
res[level].push_back(root->val);
if (root->left) levelorder(root->left, level + 1, res);
if (root->right) levelorder(root->right, level + 1, res);
}
};　　```