【发布时间】:2018-05-16 00:09:21
【问题描述】:
我试图在 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;
}
请让我知道我在这里缺少什么。
【问题讨论】:
标签: c data-structures binary-search-tree