题目来源:
leetcode题目,网址:LCR 150. 彩灯装饰记录 II - 力扣(LeetCode)
解题思路:
广度优先遍历的同时保存每一层的节点值即可。
解题代码:
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- vector<vector<int>> decorateRecord(TreeNode* root) {
- vector<vector<int>> res;
- if(root==nullptr){
- return res;
- }
- queue<TreeNode*> q;
- q.push(root);
- while(!q.empty()){
- vector<int> temp;
- int size=q.size();
- for(int i=0;i<size;i++){
- TreeNode* thisNode=q.front();
- q.pop();
- temp.push_back(thisNode->val);
- if(thisNode->left!=nullptr){
- q.push(thisNode->left);
- }
- if(thisNode->right!=nullptr){
- q.push(thisNode->right);
- }
- }
- res.push_back(temp);
- }
- return res;
- }
- };
总结:
无官方题解。