大家好,又见面了,我是你们的朋友全栈君。
二叉树层序遍历C语言版
leetcode 102
/**
* 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().
*/
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
* returnSize = 0;
* returnColumnSizes = malloc(sizeof(int) * 2010);
if(root == NULL){
return 0;
}
int i = 0;
struct TreeNode* node;
int front=0, top = 0;
struct TreeNode** q = malloc(sizeof(struct TreeNode*) * 2010);
int** ret = malloc(sizeof(int*) * 2010);
q[top++] = root; //q[0] = root
// 队列为空 top==front
while(top - front > 0){
int q_size = top - front;
(* returnColumnSizes)[i] = q_size;
ret[i] = malloc(sizeof(int) * q_size);
for(int j =0; j < q_size;j++){
node = q[front++]; //出队
ret[i][j] = node->val;
if(node->left != NULL) q[top++]= node->left; // push
if(node->right != NULL) q[top++]= node->right;
}
i++;
}
* returnSize = i;
return ret;
}
挺有意思的
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/143573.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...