1 /* ternary.c - Ternary Search Trees
2 Copyright (C) 2001 Free Software Foundation, Inc.
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
30 #include "libiberty.h"
33 /* Non-recursive so we don't waste stack space/time on large
37 ternary_insert (root, s, data, replace)
44 ternary_tree curr, *pcurr;
46 /* Start at the root. */
48 /* Loop until we find the right position */
49 while ((curr = *pcurr))
51 /* Calculate the difference */
52 diff = *s - curr->splitchar;
53 /* Handle current char equal to node splitchar */
56 /* Handle the case of a string we already have */
60 curr->eqkid = (ternary_tree) data;
61 return (PTR) curr->eqkid;
63 pcurr = &(curr->eqkid);
65 /* Handle current char less than node splitchar */
68 pcurr = &(curr->lokid);
70 /* Handle current char greater than node splitchar */
73 pcurr = &(curr->hikid);
76 /* It's not a duplicate string, and we should insert what's left of
77 the string, into the tree rooted at curr */
80 /* Allocate the memory for the node, and fill it in */
81 *pcurr = (ternary_tree) xmalloc (sizeof (ternary_node));
84 curr->lokid = curr->hikid = curr->eqkid = 0;
86 /* Place nodes until we hit the end of the string.
87 When we hit it, place the data in the right place, and
92 curr->eqkid = (ternary_tree) data;
95 pcurr = &(curr->eqkid);
99 /* Free the ternary search tree rooted at p. */
106 ternary_cleanup (p->lokid);
108 ternary_cleanup (p->eqkid);
109 ternary_cleanup (p->hikid);
114 /* Non-recursive find of a string in the ternary tree */
116 ternary_search (p, s)
117 const ternary_node *p;
120 const ternary_node *curr;
124 /* Loop while we haven't hit a NULL node or returned */
127 /* Calculate the difference */
128 diff = spchar - curr->splitchar;
129 /* Handle the equal case */
133 return (PTR) curr->eqkid;
137 /* Handle the less than case */
140 /* All that's left is greater than */
147 /* For those who care, the recursive version of the search. Useful if
148 you want a starting point for pmsearch or nearsearch. */
150 ternary_recursivesearch (p, s)
151 const ternary_node *p;
156 if (*s < p->splitchar)
157 return ternary_recursivesearch (p->lokid, s);
158 else if (*s > p->splitchar)
159 return ternary_recursivesearch (p->hikid, s);
163 return (PTR) p->eqkid;
164 return ternary_recursivesearch (p->eqkid, ++s);