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

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]


Example 2:

Input: root = [1]
Output: [[1]]


Example 3:

Input: root = []
Output: []


Constraints:

• The number of nodes in the tree is in the range [0, 2000].
• -1000 <= Node.val <= 1000

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

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* node, int level, vector<vector<int>>& res) {
if (!node) return;
if (res.size() == level) res.push_back({});
res[level].push_back(node->val);
if (node->left) levelorder(node->left, level + 1, res);
if (node->right) levelorder(node->right, level + 1, res);
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/107

Average of Levels in Binary Tree

Binary Tree Zigzag Level Order Traversal

Binary Tree Level Order Traversal

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

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/35089/Java-Solution.-Using-Queue

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/34981/My-DFS-and-BFS-java-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2014-10-26 05:23  Grandyang  阅读(13336)  评论(1编辑  收藏  举报