层序遍历再反转结果
时间复杂度:O(N)
C++代码:
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if (root == nullptr)
return {};
queue<pair<TreeNode*, int>> record;
vector<vector<int>> result;
record.push(make_pair(root, 1));
while (!record.empty())
{
auto temp = record.front();
record.pop();
if (temp.second >result.size())
{
result.push_back({ temp.first->val });
}
else
{
result[result.size() - 1].push_back(temp.first->val);
}
if (temp.first->left != nullptr)
record.push(make_pair(temp.first->left, temp.second + 1));
if (temp.first->right != nullptr)
record.push(make_pair(temp.first->right, temp.second + 1));
}
reverse(result.begin(), result.end());
return result;
}
};```