题目
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语言