【模板】二叉搜索树(二叉排序树,二叉查找树,BST)

二叉搜索树其实就是满足左结点小于根,右结点大于根这类规则的树形结构。 

 1 int n;
 2 int a[MAX_N];
 3 int lt[MAX_N], rt[MAX_N];
 4 // 没有则为-1
 5 // 默认a[0]为根结点
 6  
 7 void Insert(int x, int obj) // 插入结点a[obj] 
 8 { 
 9     if(a[obj] < a[x])
10     {
11         if(lt[x] ^ -1) Insert(lt[x], obj);
12         else lt[x] = obj;
13     }
14     else
15     {
16         if(rt[x] ^ -1) Insert(rt[x], obj);
17         else rt[x] = obj;
18     }
19     return;
20 }
21  
22 int Find(int x, int obj) // 寻找obj这个值在树中的位置 
23 {
24     if(obj < a[x])
25     {
26         if(lt[x] ^ -1) return Find(lt[x], obj);
27         else return -1; // Not found
28     }
29     if(obj > a[x])
30     {
31         if(rt[x] ^ -1) return Find(rt[x], obj);
32         else return -1; // Not found
33     }
34     return x;
35 }

猜你喜欢

转载自www.cnblogs.com/kcn999/p/10015352.html