日野弥生:勉強しよう
LeetCode LCR 150 - 彩灯装饰记录 II
发表于2025年03月14日
层次遍历可处理该问题。
class Solution {
public:
vector<vector<int>> decorateRecord(TreeNode* root) {
if(!root)
return {};
queue<pair<TreeNode*, int>> q;
vector<vector<int>> result{};
q.push(make_pair(root, 0));
while(!q.empty())
{
auto curr = q.front();
q.pop();
if(curr.second >= (int)result.size())
{
vector<int> floorResult{};
floorResult.push_back(curr.first->val);
result.push_back(floorResult);
}
else
{
result[curr.second].push_back(curr.first->val);
}
if(curr.first->left)
q.push({curr.first->left, curr.second + 1});
if(curr.first->right)
q.push({curr.first->right, curr.second + 1});
}
return result;
}
};