0
我正在嘗試創建一個將創建最大堆樹的函數。二叉樹上的最大堆積
問題是 ,我想我的函數返回此樹的根,但我不知道該怎麼做。 我認爲在這裏(1)和這裏(2)的行會使該函數在插入前返回最後一個節點,我想不出讓它返回樹的根的簡單方法。
typedef struct node{
int n;
struct node* right;
struct node* left;
}node;
node * f(node* root, int v){
node* p;
if(!root){ //creating new node;
p = malloc(sizeof(node));
p->n = v;
p->right = NULL;
p->left = NULL;
return p;
}
if(v > root->n){ //if v is greater than the node, they'll be swapped.
int aux = root->n;
root->n = v;
return f(root->right, aux); //here(1)
}
//if v is smaller than the node, f will be called to the left node.
if(v < root->n){
int aux = root->n;
return f(root->left, aux); //here(2)
}
return root;
}
看來,因爲你不交換指針,只是值,樹的根不會改變。你需要通過返回來跟蹤它嗎? –
我不相信你的代碼會創建一個有效的二進制堆樹。請注意,您並未在任何地方更新節點「左」或「右」值,因此您沒有鏈接節點。 – ericbn
此外,如果您按照新月順序添加值,則該樹將一直保持不變,從而更好地檢查您的算法! – ericbn