二叉树搜索树(无左旋右旋)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);
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页