1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| //修改以适应 insert_node,如果树为空或已找到节点,返回null。否则,返回指向查找过程中遇到树中最后一个节点的指针。
tree_pointer modified_search(tree_pointer tree,int key){
if(!tree) return NULL;
while(tree){
if(tree->data == key) return NULL;
if(key < tree->data) {
if(tree->left_child) break;
tree=tree->left_child;
}else{
if(tree->right_child) break;
tree=tree->right_child;
}
}
return tree;
}
void insert_node(tree_pointer *node,int num){
// if num is in the tree pointed at by node do nothing;
tree_pointer ptr,temp=modified_search(*node, num);
if(temp || !(*node)){
ptr = (tree_pointer) malloc (sizeof(tree_node));
if(!ptr){
fprintf(stderr, "full");
exit(1);
}
ptr->data=num;
ptr->left_child=ptr->right_child=NULL;
if(*node){
if(num < temp->data) temp->left_child = ptr;
else temp->right_child = ptr;
} else {
*node = ptr;
}
}
}
|