2024年6月16日 星期日

[144] Binary Tree Preorder Traversal

意外的順利(?)真是嚇到我了。

該驚嚇的是,這題妳竟然還沒有寫過吧XD
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/


/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void dfs(struct TreeNode* root, int *arr, int *idx)
{
if (root == NULL)
return;
arr[*idx] = root->val;
(*idx)++;
dfs(root->left, arr, idx);
dfs(root->right, arr, idx);
return;
}

int* preorderTraversal(struct TreeNode* root, int* returnSize){
int *ret = calloc (101, sizeof(int));
int idx =0;
dfs(root, ret, &idx);
*returnSize = idx;
return ret;
}

沒有留言:

張貼留言