//二t叉?搜?索??树???的??搜?索?? #include <stdio.h> #include <stdlib.h> typedef int KeyType; typedef struct node{ KeyType key; struct node *lchild,*rchild; }BSTNode; int Compare(int index1,int index2) { if(index1>index2) return 1; if(index1<index2) return -1; return 0; } BSTNode * bst_search(BSTNode* t,KeyType k) { if(t==NULL) return NULL; else { switch(Compare(k,t->key)) { case 0: return (t); case 1: return (bst_search(t->rchild,k)); case -1: return (bst_search(t->lchild,k)); } } } void main() { BSTNode * ptrtemp = NULL; ptrtemp = (BSTNode*)malloc( sizeof(BSTNode)); ptrtemp->key = 30; BSTNode* l1,*r1,*l2; l1=(BSTNode*)malloc( sizeof(BSTNode)); r1=(BSTNode*)malloc( sizeof(BSTNode)); l2=(BSTNode*)malloc( sizeof(BSTNode)); ptrtemp->lchild = l1; ptrtemp->rchild = r1; l1->lchild = l2; l1->key = 5; l1->rchild = NULL; r1->key = 40; r1->lchild = NULL; r1->rchild = NULL; l2->key = 2; l2->lchild =NULL; l2->rchild = NULL; BSTNode* result; KeyType searched =2; result = bst_search(ptrtemp,searched); if(result!=NULL) printf( "%d",result->key); }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步