【leetcode】列印二叉樹連結串列
阿新 • • 發佈:2020-08-23
int count = 0;
void func(int** arr,int* hash,struct TreeNode* node,int row)
{
row++;
if (hash[row] == 0) //如果該行列數為0 那證明是當前遍歷到的是該行第一個數(空值已經排除)
{
count++;
int* row_arr = (int*)calloc(1000,sizeof(int));
arr[row] = row_arr;
row_arr[hash[row]++] = node->val; //賦值完後列數+1
}
else if(hash[row] > 0)
{
arr[row][hash[row]++] = node->val;
}
if (node->left != NULL)
{
func(arr,hash,node->left,row);
}
if (node->right != NULL)
{
func(arr,hash,node->right,row);
}
}
int** levelOrder(struct TreeNode* root, int * returnSize, int** returnColumnSizes){
int** arr = (int**)calloc(10000,sizeof(int));
int* hash = (int*)calloc(10000,sizeof(int)); //用來存放每行的列數
if (root == NULL)
{
*returnSize = NULL;
return NULL;
}
int* row_arr = (int*)calloc(1,sizeof(int));
int row = 0; //行數
count = 0 ; //定義了全域性變數 用來最後返回行數
row_arr[hash[row]++] = root->val;
arr[row] = row_arr;
count++;
if (root->left != NULL)
{
func(arr,hash,root->left,row);
}
if (root->right != NULL)
{
func(arr,hash,root->right,row);
}
*returnSize = count; //行數
*returnColumnSizes = hash; //每行列數指標
return arr;
}