我已经了解了C中BST的实现。
以下是代码:
#include <stdio.h>
#include <stdlib.h>
struct tree{
int data;
struct tree *left;
struct tree *right;
};
struct tree *newnode(int );
struct tree *insert(int , struct tree *);
void inorder(struct tree *);
int main(){
struct tree *root = NULL;
root = insert(5, root);
root = insert(3, root);
root = insert(4, root);
root = insert(2, root);
root = insert(7, root);
root = insert(6, root);
root = insert(8, root);
root = insert(9, root);
printf("\nInorder Traversal : \n");
inorder(root);
return 0;
}
struct tree *newnode(int data){
struct tree *new = (struct tree *)malloc(sizeof(struct tree));
new->data = data;
new->left = NULL;
new->right = NULL;
return new;
}
struct tree *insert(int data, struct tree *root){
if(!root){
printf("For %d\n",data);
root = newnode(data);
}
else if(root->data >= data ){ /* Push this into left subtree */
printf("Else if : For %d\n",data);
root = insert(data, root->left);
}
else{ /* Push this into left subtree */
printf("Else : For %d\n",data);
root = insert(data, root->right);
}
return root;
}
void inorder(struct tree *root){
if(root){
inorder(root->left);
printf(" %d",root->data);
inorder(root->right);
}
}
每当我运行程序时,我都没有得到所需的输出。也就是说,上面的代码应该打印出这样的内容:
1 2 3 4 5 6 7 8 9
但它会打印9
,就是这样。
我已经彻底检查了代码,经历了所有可能的极端情况,对我来说似乎很好。
递归函数insert
看起来很完美。但是,不知何故,root
指针始终指向插入的最后一个节点。
答案 0 :(得分:1)
感谢@Someprogrammerdude指出。
在df$Data[!grepl('^[A-Za-z]+$', df$Data)] <- 'ABC'
函数中,我应该这样做:
insert
因此,struct tree *insert(int data, struct tree *root){
if(!root){
root = newnode(data);
}
else if(root->data >= data ) /* Push this into left subtree */
root->left = insert(data, root->left);
else /* Push this into left subtree */
root->right = insert(data, root->right);
return root;
}
和root->left
对作业非常重要。