# 二叉树搜索树（无左旋右旋）C 迭代寻找插入

#include <stdio.h>
#include <stdlib.h>

typedef struct tree_t{
int index;
struct tree_t *l_node,*r_node;
}tree;

#define FALSE 0
#define TRUE 1

int search(tree *node,unsigned int index,tree **new_node)
{

tree *pre_node = NULL;
while(TRUE){
if(node == NULL){
*new_node = pre_node;
return FALSE;
}

if(index == node->index){
*new_node = node;
return TRUE;
}else if(index < node->index){
pre_node = node;
node = node->l_node;
}else{
pre_node = node;
node = node->r_node;
}
}
}

int insert(tree **node,unsigned int id){
tree *tmp =  NULL;

if(!search((*node),id,&tmp)){
tree *new_node = (tree*)malloc(sizeof(tree));
new_node->index = id;
if(tmp == NULL){
*node = new_node;
}else if(id < tmp->index){
tmp->l_node = new_node;
}else{
tmp->r_node = new_node;
}
return TRUE;
}
return FALSE;
}

void print(tree *t){
if(t == NULL){
return;
}
print(t->l_node);
printf("%d",t->index);
print(t->r_node);
}

int main(void){
unsigned int id[3] = {1,2,4};
tree *param = NULL;
for(int i = 0 ; i < 3 ; i++){
printf("%d\n",insert(&param,id[i]));
}
print(param);
}


05-20 522

11-16 52
03-03 9637
08-23 500
05-19 1176
04-17 1475
03-18 177
07-09 945
07-22 131
05-02 194