5 static inline int height(struct node
*n
) { return n
? n
->h
: 0; }
7 static int rot(void **p
, struct node
*x
, int dir
/* deeper side */)
9 struct node
*y
= x
->a
[dir
];
10 struct node
*z
= y
->a
[!dir
];
13 if (hz
> height(y
->a
[dir
])) {
23 x
->a
[dir
] = z
->a
[!dir
];
24 y
->a
[!dir
] = z
->a
[dir
];
48 /* balance *p, return 0 if height is unchanged. */
49 int __tsearch_balance(void **p
)
52 int h0
= height(n
->a
[0]);
53 int h1
= height(n
->a
[1]);
54 if (h0
- h1
+ 1u < 3u) {
56 n
->h
= h0
<h1
? h1
+1 : h0
+1;
59 return rot(p
, n
, h0
<h1
);
62 void *tsearch(const void *key
, void **rootp
,
63 int (*cmp
)(const void *, const void *))
69 struct node
*n
= *rootp
;
76 int c
= cmp(key
, n
->key
);
82 r
= malloc(sizeof *r
);
86 r
->a
[0] = r
->a
[1] = 0;
88 /* insert new node, rebalance ancestors. */
90 while (i
&& __tsearch_balance(a
[--i
]));