2025年10月6日 星期一

[589] N-ary Tree Preorder Traversal

別人的code 總是好漂亮啊~(讚嘆)
算惹至少我也沒有誤入歧途太久就寫好了,修好的版本如下兒~
原來return Size 可以直接拿來用!少宣告一個 count 來紀錄~很棒XD!

/**
* Definition for a Node.
* struct Node {
* int val;
* int numChildren;
* struct Node** children;
* };
*/

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void recursive(struct Node* ptr, int* ret, int* size){
if (ptr == NULL)
return;

ret[(*size)++]= ptr->val;
for (int j= 0;j<ptr->numChildren;j++)
recursive(ptr->children[j],ret, size);
return;
}


int* preorder(struct Node* root, int* returnSize) {
*returnSize = 0;
int *ret = calloc (10001,sizeof(int));
recursive(root, ret , returnSize);
return ret;
}

沒有留言:

張貼留言