![](/img/trans.png)
[英]Tree traversal (preorder,inorder,postorder) print result change
[英]Preorder tree traversal works but postorder doesn't
我有兩個函數以preorder
和postorder
遍歷樹,每個函數將節點中的值插入到一個數組中,並返回該數組。
但是,我的postorder
功能不起作用。 調用該函數時出現分段錯誤。
編譯並運行以下代碼時,但在調用postorder
方法postorder
出現分段錯誤。
這是我的代碼:
int* preorder_recursive(node *root, int* dataArray)
{
if (root == NULL)
return dataArray;
for (int i = 0; i < 512; i++)
{
if (dataArray[i] == INT_MIN)
{
dataArray[i] = root->data;
printf("%d is being inserted to the preorder array at pos %d\n", root->data, i);
break;
}
}
preorder_recursive(root->left, dataArray);
preorder_recursive(root->right, dataArray);
}
int* postorder_recursive(node *root, int *dataArray)
{
if (root == NULL)
return dataArray;
postorder_recursive(root->left, dataArray);
postorder_recursive(root->right, dataArray);
for (int i = 0; i < 512; i++)
{
// any "empty" spots in the array should contain INT_MIN
if (dataArray[i] == INT_MIN)
{
dataArray[i] = root->data;
printf("%d is being inserted to the postorder array at pos %d\n", root->data, i);
break;
}
}
}
調用時:
int * complete_pre_b = preorder_recursive(b, pre_order_b);
for(int i = 0; i < 3; i++)
{
printf("pre b is %d\n", complete_pre_b[i]);
}
int * complete_post_b = postorder_recursive(b, post_order_b);
// here is the last print I see - code get till here fine
for(int i = 0; i < 3; i++)
{
printf("post b is %d\n", complete_post_b[i]);
}
(注意- 我有 3 個節點的樹,為什么我從 0 到 3 循環)
可能是什么問題? 我的post和pre order有什么不同?
請注意,您這樣做: complete_post_b = postorder_recursive(b, post_order_b);
當complete_post_b
在main
的開頭定義為: int* complete_post_b;
但是,在postorder_recursive
您不返回任何數據。 所以當分配給complete_post_b
它實際上是無效的。
你的 for 循環應該是:
for(int i = 0; i < 3; i++)
{
printf("post b is %d\n", post_order_b[i]); // and not complete_post_b
}
或者您可以返回dataArray
並使用complete_post_b
。
對於興趣部分:為什么它只發生在 postOrder 上?
請注意,只有當節點為空時才返回dataArray
。 我的猜測是在這種情況下,返回值的寄存器將包含數據數組。 在函數末尾進行遞歸函數調用時,數據數組的地址保留在寄存器中並向前傳輸 - 但您不能指望這一點,如果您想使用它,您需要實際返回地址
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.