当前位置:   article > 正文

每日一道算法题 彩灯装饰记录 I

每日一道算法题 彩灯装饰记录 I

题目

LCR 149. 彩灯装饰记录 I - 力扣(LeetCode)

Python

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def decorateRecord(self, root: Optional[TreeNode]) -> List[int]:
  9. if not root:return []
  10. qu=[root]
  11. ans=[]
  12. while qu:
  13. cur=qu.pop(0)
  14. ans.append(cur.val)
  15. if cur.left:
  16. qu.append(cur.left)
  17. if cur.right:
  18. qu.append(cur.right)
  19. return ans

C++

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. vector<int> decorateRecord(TreeNode* root)
  15. {
  16. vector<int> ans;
  17. if(!root) return ans;
  18. queue<TreeNode*> qu;
  19. qu.push(root);
  20. while(!qu.empty())
  21. {
  22. TreeNode* cur=qu.front();
  23. qu.pop();
  24. ans.push_back(cur->val);
  25. if(cur->left) qu.push(cur->left);
  26. if(cur->right) qu.push(cur->right);
  27. }
  28. return ans;
  29. }
  30. };

C语言

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * struct TreeNode *left;
  6. * struct TreeNode *right;
  7. * };
  8. */
  9. /**
  10. * Note: The returned array must be malloced, assume caller calls free().
  11. */
  12. int* decorateRecord(struct TreeNode* root, int* returnSize)
  13. {
  14. int* ans=(int*)malloc(sizeof(int)*1100);
  15. if(root==NULL)
  16. {
  17. *returnSize=0;
  18. return ans;
  19. }
  20. struct TreeNode* qu[1100];
  21. struct TreeNode* cur;
  22. int size=0;
  23. int front=0;
  24. int rear=0;
  25. qu[rear++]=root;
  26. while(front<rear)
  27. {
  28. cur=qu[front++];
  29. ans[size++]=cur->val;
  30. if(cur->left) qu[rear++]=cur->left;
  31. if(cur->right) qu[rear++]=cur->right;
  32. }
  33. *returnSize=size;
  34. return ans;
  35. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/796379
推荐阅读
相关标签
  

闽ICP备14008679号