[英]What is wrong with the following binary tree inorder traversal?
做https://leetcode.com/problems/binary-tree-inorder-traversal/ 。 問題如下
給定二叉樹的根,返回其節點值的中序遍歷。
以下結構用作二叉樹節點。
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
下面是我提交給 leetcode 的代碼。
void inOrderTraversalHelper(struct TreeNode* root, int* returnSize, int** result_ref) {
if (root != NULL) {
inOrderTraversalHelper(root->left, returnSize, result_ref);
if (*returnSize == 0) {
*result_ref = malloc(sizeof(int));
} else {
*result_ref = realloc(*result_ref,
(sizeof(int) * (*returnSize + 1)));
}
*((*result_ref) + *returnSize) = root->val;
*returnSize = *returnSize + 1;
inOrderTraversalHelper(root->right, returnSize, result_ref);
}
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int* result = NULL;
int ** result_ref = &result;
returnSize = malloc(sizeof(int));
*returnSize = 0;
if (root != NULL) {
inOrderTraversalHelper(root, returnSize, result_ref);
}
return result;
}
我在 leetcode 上運行上面的代碼。 它沒有通過第一個測試用例 ([1,null,2,3])。 我的代碼只輸出“]”。
我覺得我幾乎肯定會錯誤地使用 malloc 和 realloc,但我不確定如何。
我的代碼很好,除了這一行
returnSize = malloc(sizeof(int));
我正在更改 returnSize 指向的內存塊。 它已經被它的調用者分配了內存,我不應該在這里使用 malloc。 這導致 leetcode 訪問了我返回值的錯誤部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.