我試圖給每個節點的數據添加+1,除了具有最小數字的節點之外。到目前爲止,我的實現不正確,我在遞歸調用中迷路了。我的代碼在某些情況下添加不正確,在必要時不添加。我明白要找到最小的一塊數據,我們繼續向左連接的節點(8),在這種情況下,我是否缺少某些測試條件?向BST中的所有節點遞歸地添加1,除了具有SMALLEST數據的節點以外
Given a data set: 8, 14, 24, 29, 31, 35, 46, 58, 62,85, 95
Expected results: 8, 15, 25, 30, 32, 36, 47, 59, 63, 86, 96
Actual results: 9, 14, 25, 29, 32, 36, 46, 59, 63, 85, 96
struct node
{
node * left;
node * right;
int data;
};
int add1(node * root)
{
if(!root) return 0;
add1(root->left); //go left
if(!root->left) { //if left is NULL
if(root->right) //check if there is a right child
add1(root->right); //go to that node
else
return 0;
}
root->data += 1; //add 1 to node
add1(root->right); //go right
return 1;
}
int main()
{
node * root = NULL;
build(root); //inserts data set into our tree
display(root);
add1(root);
display(root);
return 0;
}
對不起,你的意思是添加我的節點的結構? –
yep節點聲明和初始化 – em2er