我正在尝试在BST中插入元素而没有获得正确的结果。
我没有打印出所有数组元素,而只打印1,11,14
元素而不是整个数组元素。
int arr[10] = { 11, 2, 4, 23, 1, 98, 88, 65, 33, 14 };
void insertNodeinBST(int data,node **root){
node *new_n = (node*)malloc(sizeof(node));
new_n->leftChild = new_n->rightChild = NULL;
new_n->data = data;
//check if root is null
if (*root == NULL) {
*root = new_n;
}
else if (data < (*root)->data){
//if data is less than current root's data add it to left child
insertNodeinBST(data, &(*root)->leftChild);
(*root)->leftChild = new_n;
}
else {
//if data is more than current root's data add it to right child
insertNodeinBST(data, &(*root)->rightChild);
(*root)->rightChild = new_n;
}
}
//print BST
void printInorder(node *root){
if (root == NULL)
return;
/* first recur on left child */
printInorder(root->leftChild);
/* then print the data of node */
printf("%d ", root->data);
/* now recur on right child */
printInorder(root->rightChild);
}
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
node *root = NULL;
for (i = 0; i < 10; i++){
//inserting nodes
insertNodeinBST(arr[i], &root);
}
printInorder(root);
return 0;
}
请告诉我这里缺少的东西。
答案 0 :(得分:1)
你几乎拥有它,只有insertNodeinBST()
中的几件事:
您应该只在root
为NULL
时创建新节点,否则,每次访问新节点时都会继续创建新节点,寻找要插入的位置:
//check if root is null
if (*root == NULL) {
node *new_n = (node*)malloc(sizeof(node));
new_n->leftChild = new_n->rightChild = NULL;
new_n->data = data;
*root = new_n;
}
上面的代码负责插入新节点,因此您不需要其他分配,更改:
} else if (data < (*root)->data) {
//if data is less than current root's data add it to left child
insertNodeinBST(data, &(*root)->leftChild);
(*root)->leftChild = new_n;
} else {
//if data is more than current root's data add it to right child
insertNodeinBST(data, &(*root)->rightChild);
(*root)->rightChild = new_n;
}
到
} else if (data < (*root)->data) {
//if data is less than current root's data add it to left child
insertNodeinBST(data, &(*root)->leftChild);
} else {
//if data is more than current root's data add it to right child
insertNodeinBST(data, &(*root)->rightChild);
}
递归调用将在到达正确的空节点时将指针设置为新节点。