2023每日刷题(二十四)
Leetcode—102.二叉树的层序遍历
C语言BFS实现代码
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/
/*** Return an array of arrays of size *returnSize.* The sizes of the arrays are returned as *returnColumnSizes array.* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().*/
#define MAXSIZE 2003int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {*returnSize = 0;if(root == NULL) {return NULL;}*returnColumnSizes = (int *)malloc(sizeof(int) * MAXSIZE);int** ans = (int **)malloc(sizeof(int *) * MAXSIZE);struct TreeNode** queue = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * MAXSIZE);int front = 0, rear = 0;int len = 0;int pos = 0;queue[rear++] = root;while(front != rear) {len = rear - front;ans[*returnSize] = (int *)malloc(sizeof(int) * len);int cnt = 0;while(len > 0) {len--;struct TreeNode* tmp = queue[front++];ans[*returnSize][cnt++] = tmp->val;if(tmp->left) {queue[rear++] = tmp->left;}if(tmp->right) {queue[rear++] = tmp->right;}}(*returnColumnSizes)[*returnSize] = cnt;(*returnSize)++;}return ans;
}
运行结果
C++BFS实现代码
/*** 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>> levelOrder(TreeNode* root) {vector<vector<int>> ans;if(root == NULL) {return ans;}TreeNode *p;queue<TreeNode*>qu;qu.push(root);vector<int>anslevel;while(!qu.empty()) {int n = qu.size();for(int i = 0; i < n; i++) {p = qu.front();qu.pop();anslevel.push_back(p->val);if(p->left != NULL) {qu.push(p->left);}if(p->right != NULL) {qu.push(p->right);}}ans.push_back(anslevel);anslevel.clear();}return ans;}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!