Bootstrap

每日一道算法题 LCR 151. 彩灯装饰记录 III

题目

LCR 151. 彩灯装饰记录 III - 力扣(LeetCode)

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def decorateRecord(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        ans=[]
        qu=[root]
        flag=0
        while qu:
            row=[]
            le=len(qu)
            for _ in range(le):
                cur=qu.pop(0)
                row.append(cur.val)
                if cur.left:
                    qu.append(cur.left)
                if cur.right:
                    qu.append(cur.right)
            if not flag:
                ans.append(row)
            else:
                ans.append(row[::-1])
            flag=not flag
            # ans.append(row)
        return ans

C++

/**
 * 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>> ans;
        if(root==NULL) return ans;
        queue<TreeNode*> qu;
        qu.push(root);
       
        int lay=1; //层数

        while(!qu.empty())
        {
            vector<int> row;
            TreeNode* cur=NULL;
            int le=qu.size();
            for(int _=0;_<le;_++)
            {
                cur=qu.front();
                qu.pop();
                if(lay%2==0) row.push_back(cur->val);
                else row.insert(row.begin(),cur->val);
                   
                if(cur->right) qu.push(cur->right);
                if(cur->left) qu.push(cur->left);
            }
            lay++;
            ans.push_back(row);
        }

        return ans;
    }
};

C语言

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;