题目:
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] ]
思路:
这道题目和Leetcode 102的唯一区别就是最后需要把结果翻转一下,具体请参加我的Leetcode 102解题报告。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if (root == NULL) {
return {};
}
vector<vector<int>> ret;
queue<TreeNode*> q;
q.push(root);
q.push(NULL); // separator
vector<int> line;
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node == NULL) {
ret.push_back(line);
line.clear();
if (!q.empty()) {
q.push(NULL);
}
}
else {
line.push_back(node->val);
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
}
reverse(ret.begin(), ret.end()); // the only difference with Leetcode 102
return ret;
}
};