1 ;;; avl-tree.el --- balanced binary trees, AVL-trees -*- lexical-binding:t -*-
3 ;; Copyright (C) 1995, 2007-2016 Free Software Foundation, Inc.
5 ;; Author: Per Cederqvist <ceder@lysator.liu.se>
6 ;; Inge Wallin <inge@lysator.liu.se>
7 ;; Thomas Bellman <bellman@lysator.liu.se>
8 ;; Toby Cubitt <toby-predictive@dr-qubit.org>
9 ;; Maintainer: emacs-devel@gnu.org
10 ;; Created: 10 May 1991
11 ;; Keywords: extensions, data structures, AVL, tree
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation, either version 3 of the License, or
18 ;; (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
30 ;; An AVL tree is a self-balancing binary tree. As such, inserting,
31 ;; deleting, and retrieving data from an AVL tree containing n elements
32 ;; is O(log n). It is somewhat more rigidly balanced than other
33 ;; self-balancing binary trees (such as red-black trees and AA trees),
34 ;; making insertion slightly slower, deletion somewhat slower, and
35 ;; retrieval somewhat faster (the asymptotic scaling is of course the
36 ;; same for all types). Thus it may be a good choice when the tree will
37 ;; be relatively static, i.e. data will be retrieved more often than
40 ;; Internally, a tree consists of two elements, the root node and the
41 ;; comparison function. The actual tree has a dummy node as its root
42 ;; with the real root in the left pointer, which allows the root node to
43 ;; be treated on a par with all other nodes.
45 ;; Each node of the tree consists of one data element, one left
46 ;; sub-tree, one right sub-tree, and a balance count. The latter is the
47 ;; difference in depth of the left and right sub-trees.
49 ;; The functions with names of the form "avl-tree--" are intended for
54 (eval-when-compile (require 'cl-lib
))
58 ;; ================================================================
59 ;;; Internal functions and macros for use in the AVL tree package
62 ;; ----------------------------------------------------------------
63 ;; Functions and macros handling an AVL tree.
65 (cl-defstruct (avl-tree-
66 ;; A tagged list is the pre-defstruct representation.
70 (:constructor avl-tree--create
(cmpfun))
71 (:predicate avl-tree-p
)
73 (dummyroot (avl-tree--node-create nil nil nil
0))
76 (defmacro avl-tree--root
(tree)
77 ;; Return the root node for an AVL tree. INTERNAL USE ONLY.
78 `(avl-tree--node-left (avl-tree--dummyroot ,tree
)))
80 ;; ----------------------------------------------------------------
81 ;; Functions and macros handling an AVL tree node.
83 (cl-defstruct (avl-tree--node
84 ;; We force a representation without tag so it matches the
85 ;; pre-defstruct representation. Also we use the underlying
86 ;; representation in the implementation of
87 ;; avl-tree--node-branch.
90 (:constructor avl-tree--node-create
(left right data balance
))
92 left right data balance
)
95 (defalias 'avl-tree--node-branch
#'aref
96 ;; This implementation is efficient but breaks the defstruct
97 ;; abstraction. An alternative could be (funcall (aref [avl-tree-left
98 ;; avl-tree-right avl-tree-data] branch) node)
99 "Get value of a branch of a node.
100 NODE is the node, and BRANCH is the branch.
101 0 for left pointer, 1 for right pointer and 2 for the data.")
104 ;; The funcall/aref trick wouldn't work for the setf method, unless we
105 ;; tried to access the underlying setter function, but this wouldn't be
107 (gv-define-simple-setter avl-tree--node-branch aset
)
111 ;; ----------------------------------------------------------------
112 ;; Convenience macros
114 (defmacro avl-tree--switch-dir
(dir)
115 "Return opposite direction to DIR (0 = left, 1 = right)."
118 (defmacro avl-tree--dir-to-sign
(dir)
119 "Convert direction (0,1) to sign factor (-1,+1)."
122 (defmacro avl-tree--sign-to-dir
(dir)
123 "Convert sign factor (-x,+x) to direction (0,1)."
124 `(if (< ,dir
0) 0 1))
127 ;; ----------------------------------------------------------------
130 (defun avl-tree--del-balance (node branch dir
)
131 "Rebalance a tree after deleting a node.
132 The deletion was done from the left (DIR=0) or right (DIR=1) sub-tree of the
133 left (BRANCH=0) or right (BRANCH=1) child of NODE.
134 Return t if the height of the tree has shrunk."
135 ;; (or is it vice-versa for BRANCH?)
136 (let ((br (avl-tree--node-branch node branch
))
137 ;; opposite direction: 0,1 -> 1,0
138 (opp (avl-tree--switch-dir dir
))
139 ;; direction 0,1 -> sign factor -1,+1
140 (sgn (avl-tree--dir-to-sign dir
))
143 ((> (* sgn
(avl-tree--node-balance br
)) 0)
144 (setf (avl-tree--node-balance br
) 0)
147 ((= (avl-tree--node-balance br
) 0)
148 (setf (avl-tree--node-balance br
) (- sgn
))
153 (setq p1
(avl-tree--node-branch br opp
)
154 b1
(avl-tree--node-balance p1
))
155 (if (<= (* sgn b1
) 0)
158 (setf (avl-tree--node-branch br opp
)
159 (avl-tree--node-branch p1 dir
)
160 (avl-tree--node-branch p1 dir
) br
161 (avl-tree--node-branch node branch
) p1
)
164 (setf (avl-tree--node-balance br
) (- sgn
)
165 (avl-tree--node-balance p1
) sgn
)
166 nil
) ; height hasn't changed
167 (setf (avl-tree--node-balance br
) 0)
168 (setf (avl-tree--node-balance p1
) 0)
169 t
)) ; height has changed
172 (setf p2
(avl-tree--node-branch p1 dir
)
173 b2
(avl-tree--node-balance p2
)
174 (avl-tree--node-branch p1 dir
)
175 (avl-tree--node-branch p2 opp
)
176 (avl-tree--node-branch p2 opp
) p1
177 (avl-tree--node-branch br opp
)
178 (avl-tree--node-branch p2 dir
)
179 (avl-tree--node-branch p2 dir
) br
180 (avl-tree--node-balance br
)
181 (if (< (* sgn b2
) 0) sgn
0)
182 (avl-tree--node-balance p1
)
183 (if (> (* sgn b2
) 0) (- sgn
) 0)
184 (avl-tree--node-branch node branch
) p2
185 (avl-tree--node-balance p2
) 0)
188 (defun avl-tree--do-del-internal (node branch q
)
189 (let ((br (avl-tree--node-branch node branch
)))
190 (if (avl-tree--node-right br
)
191 (if (avl-tree--do-del-internal br
1 q
)
192 (avl-tree--del-balance node branch
1))
193 (setf (avl-tree--node-data q
) (avl-tree--node-data br
)
194 (avl-tree--node-branch node branch
)
195 (avl-tree--node-left br
))
198 (defun avl-tree--do-delete (cmpfun root branch data test nilflag
)
199 "Delete DATA from BRANCH of node ROOT.
200 \(See `avl-tree-delete' for TEST and NILFLAG).
202 Return cons cell (SHRUNK . DATA), where SHRUNK is t if the
203 height of the tree has shrunk and nil otherwise, and DATA is
205 (let ((br (avl-tree--node-branch root branch
)))
211 ((funcall cmpfun data
(avl-tree--node-data br
))
212 (let ((ret (avl-tree--do-delete cmpfun br
0 data test nilflag
)))
213 (cons (if (car ret
) (avl-tree--del-balance root branch
0))
216 ((funcall cmpfun
(avl-tree--node-data br
) data
)
217 (let ((ret (avl-tree--do-delete cmpfun br
1 data test nilflag
)))
218 (cons (if (car ret
) (avl-tree--del-balance root branch
1))
222 ;; if it fails TEST, do nothing
223 (if (and test
(not (funcall test
(avl-tree--node-data br
))))
226 ((null (avl-tree--node-right br
))
227 (setf (avl-tree--node-branch root branch
)
228 (avl-tree--node-left br
))
229 (cons t
(avl-tree--node-data br
)))
231 ((null (avl-tree--node-left br
))
232 (setf (avl-tree--node-branch root branch
)
233 (avl-tree--node-right br
))
234 (cons t
(avl-tree--node-data br
)))
237 (if (avl-tree--do-del-internal br
0 br
)
238 (cons (avl-tree--del-balance root branch
0)
239 (avl-tree--node-data br
))
240 (cons nil
(avl-tree--node-data br
))))
245 ;; ----------------------------------------------------------------
248 (defun avl-tree--enter-balance (node branch dir
)
249 "Rebalance tree after an insertion
250 into the left (DIR=0) or right (DIR=1) sub-tree of the
251 left (BRANCH=0) or right (BRANCH=1) child of NODE.
252 Return t if the height of the tree has grown."
253 (let ((br (avl-tree--node-branch node branch
))
254 ;; opposite direction: 0,1 -> 1,0
255 (opp (avl-tree--switch-dir dir
))
256 ;; direction 0,1 -> sign factor -1,+1
257 (sgn (avl-tree--dir-to-sign dir
))
260 ((< (* sgn
(avl-tree--node-balance br
)) 0)
261 (setf (avl-tree--node-balance br
) 0)
264 ((= (avl-tree--node-balance br
) 0)
265 (setf (avl-tree--node-balance br
) sgn
)
269 ;; Tree has grown => Rebalance.
270 (setq p1
(avl-tree--node-branch br dir
))
271 (if (> (* sgn
(avl-tree--node-balance p1
)) 0)
274 (setf (avl-tree--node-branch br dir
)
275 (avl-tree--node-branch p1 opp
))
276 (setf (avl-tree--node-branch p1 opp
) br
)
277 (setf (avl-tree--node-balance br
) 0)
278 (setf (avl-tree--node-branch node branch
) p1
))
281 (setf p2
(avl-tree--node-branch p1 opp
)
282 b2
(avl-tree--node-balance p2
)
283 (avl-tree--node-branch p1 opp
)
284 (avl-tree--node-branch p2 dir
)
285 (avl-tree--node-branch p2 dir
) p1
286 (avl-tree--node-branch br dir
)
287 (avl-tree--node-branch p2 opp
)
288 (avl-tree--node-branch p2 opp
) br
289 (avl-tree--node-balance br
)
290 (if (> (* sgn b2
) 0) (- sgn
) 0)
291 (avl-tree--node-balance p1
)
292 (if (< (* sgn b2
) 0) sgn
0)
293 (avl-tree--node-branch node branch
) p2
))
294 (setf (avl-tree--node-balance
295 (avl-tree--node-branch node branch
))
299 (defun avl-tree--do-enter (cmpfun root branch data
&optional updatefun
)
300 "Enter DATA in BRANCH of ROOT node.
301 \(See `avl-tree-enter' for UPDATEFUN).
303 Return cons cell (GREW . DATA), where GREW is t if height
304 of tree ROOT has grown and nil otherwise, and DATA is the
306 (let ((br (avl-tree--node-branch root branch
)))
309 ;; Data not in tree, insert it.
310 (setf (avl-tree--node-branch root branch
)
311 (avl-tree--node-create nil nil data
0))
314 ((funcall cmpfun data
(avl-tree--node-data br
))
315 (let ((ret (avl-tree--do-enter cmpfun br
0 data updatefun
)))
316 (cons (and (car ret
) (avl-tree--enter-balance root branch
0))
319 ((funcall cmpfun
(avl-tree--node-data br
) data
)
320 (let ((ret (avl-tree--do-enter cmpfun br
1 data updatefun
)))
321 (cons (and (car ret
) (avl-tree--enter-balance root branch
1))
324 ;; Data already in tree, update it.
328 (funcall updatefun data
(avl-tree--node-data br
))
330 (if (or (funcall cmpfun newdata data
)
331 (funcall cmpfun data newdata
))
332 (error "avl-tree-enter:\
333 updated data does not match existing data"))
334 (setf (avl-tree--node-data br
) newdata
)
335 (cons nil newdata
)) ; return value
338 (defun avl-tree--check (tree)
339 "Check the tree's balance."
340 (avl-tree--check-node (avl-tree--root tree
)))
341 (defun avl-tree--check-node (node)
343 (let ((dl (avl-tree--check-node (avl-tree--node-left node
)))
344 (dr (avl-tree--check-node (avl-tree--node-right node
))))
345 (cl-assert (= (- dr dl
) (avl-tree--node-balance node
)))
348 ;; ----------------------------------------------------------------
351 ;;; INTERNAL USE ONLY
352 (defun avl-tree--mapc (map-function root dir
)
353 "Apply MAP-FUNCTION to all nodes in the tree starting with ROOT.
354 The function is applied in-order, either ascending (DIR=0) or
357 Note: MAP-FUNCTION is applied to the node and not to the data
365 (avl-tree--node-branch node dir
))
366 ;; Do the DIR subtree first.
369 (setq node
(avl-tree--node-branch node dir
)))
370 ;; Apply the function...
371 (funcall map-function node
)
372 ;; and do the opposite subtree.
373 (setq node
(if (setq go-dir
(avl-tree--node-branch
374 node
(avl-tree--switch-dir dir
)))
375 (avl-tree--node-branch
376 node
(avl-tree--switch-dir dir
))
379 ;;; INTERNAL USE ONLY
380 (defun avl-tree--do-copy (root)
381 "Copy the AVL tree with ROOT as root. Highly recursive."
384 (avl-tree--node-create
385 (avl-tree--do-copy (avl-tree--node-left root
))
386 (avl-tree--do-copy (avl-tree--node-right root
))
387 (avl-tree--node-data root
)
388 (avl-tree--node-balance root
))))
390 (cl-defstruct (avl-tree--stack
392 (:constructor avl-tree--stack-create
393 (tree &optional reverse
396 (if (avl-tree-empty tree
)
398 (list (avl-tree--root tree
))))))
402 (defalias 'avl-tree-stack-p
#'avl-tree--stack-p
403 "Return t if argument is an avl-tree-stack, nil otherwise.")
405 (defun avl-tree--stack-repopulate (stack)
406 ;; Recursively push children of the node at the head of STACK onto the
407 ;; front of the STACK, until a leaf is reached.
408 (let ((node (car (avl-tree--stack-store stack
)))
409 (dir (if (avl-tree--stack-reverse stack
) 1 0)))
410 (when node
; check for empty stack
411 (while (setq node
(avl-tree--node-branch node dir
))
412 (push node
(avl-tree--stack-store stack
))))))
415 ;; ================================================================
416 ;;; The public functions which operate on AVL trees.
418 ;; define public alias for constructors so that we can set docstring
419 (defalias 'avl-tree-create
#'avl-tree--create
420 "Create an empty AVL tree.
421 COMPARE-FUNCTION is a function which takes two arguments, A and B,
422 and returns non-nil if A is less than B, and nil otherwise.")
424 (defalias 'avl-tree-compare-function
#'avl-tree--cmpfun
425 "Return the comparison function for the AVL tree TREE.
429 (defun avl-tree-empty (tree)
430 "Return t if AVL tree TREE is empty, otherwise return nil."
431 (null (avl-tree--root tree
)))
433 (defun avl-tree-enter (tree data
&optional updatefun
)
434 "Insert DATA into the AVL tree TREE.
436 If an element that matches DATA (according to the tree's
437 comparison function, see `avl-tree-create') already exists in
438 TREE, it will be replaced by DATA by default.
440 If UPDATEFUN is supplied and an element matching DATA already
441 exists in TREE, UPDATEFUN is called with two arguments: DATA, and
442 the matching element. Its return value replaces the existing
443 element. This value *must* itself match DATA (and hence the
444 pre-existing data), or an error will occur.
446 Returns the new data."
447 (cdr (avl-tree--do-enter (avl-tree--cmpfun tree
)
448 (avl-tree--dummyroot tree
)
451 (defun avl-tree-delete (tree data
&optional test nilflag
)
452 "Delete the element matching DATA from the AVL tree TREE.
453 Matching uses the comparison function previously specified in
454 `avl-tree-create' when TREE was created.
456 Returns the deleted element, or nil if no matching element was
459 Optional argument NILFLAG specifies a value to return instead of
460 nil if nothing was deleted, so that this case can be
461 distinguished from the case of a successfully deleted null
464 If supplied, TEST specifies a test that a matching element must
465 pass before it is deleted. If a matching element is found, it is
466 passed as an argument to TEST, and is deleted only if the return
468 (cdr (avl-tree--do-delete (avl-tree--cmpfun tree
)
469 (avl-tree--dummyroot tree
)
470 0 data test nilflag
)))
473 (defun avl-tree-member (tree data
&optional nilflag
)
474 "Return the element in the AVL tree TREE which matches DATA.
475 Matching uses the comparison function previously specified in
476 `avl-tree-create' when TREE was created.
478 If there is no such element in the tree, nil is
479 returned. Optional argument NILFLAG specifies a value to return
480 instead of nil in this case. This allows non-existent elements to
481 be distinguished from a null element. (See also
482 `avl-tree-member-p', which does this for you.)"
483 (let ((node (avl-tree--root tree
))
484 (compare-function (avl-tree--cmpfun tree
)))
488 ((funcall compare-function data
(avl-tree--node-data node
))
489 (setq node
(avl-tree--node-left node
)))
490 ((funcall compare-function
(avl-tree--node-data node
) data
)
491 (setq node
(avl-tree--node-right node
)))
492 (t (throw 'found
(avl-tree--node-data node
)))))
496 (defun avl-tree-member-p (tree data
)
497 "Return t if an element matching DATA exists in the AVL tree TREE.
498 Otherwise return nil. Matching uses the comparison function
499 previously specified in `avl-tree-create' when TREE was created."
501 (not (eq (avl-tree-member tree data flag
) flag
))))
504 (defun avl-tree-map (fun tree
&optional reverse
)
505 "Modify all elements in the AVL tree TREE by applying FUNCTION.
507 Each element is replaced by the return value of FUNCTION applied
510 FUNCTION is applied to the elements in ascending order, or
511 descending order if REVERSE is non-nil."
514 (setf (avl-tree--node-data node
)
515 (funcall fun
(avl-tree--node-data node
))))
516 (avl-tree--root tree
)
520 (defun avl-tree-mapc (fun tree
&optional reverse
)
521 "Apply FUNCTION to all elements in AVL tree TREE,
522 for side-effect only.
524 FUNCTION is applied to the elements in ascending order, or
525 descending order if REVERSE is non-nil."
528 (funcall fun
(avl-tree--node-data node
)))
529 (avl-tree--root tree
)
534 (fun combinator tree
&optional reverse
)
535 "Apply FUNCTION to all elements in AVL tree TREE,
536 and combine the results using COMBINATOR.
538 The FUNCTION is applied and the results are combined in ascending
539 order, or descending order if REVERSE is non-nil."
540 (let (avl-tree-mapf--accumulate)
543 (setq avl-tree-mapf--accumulate
546 (avl-tree--node-data node
))
547 avl-tree-mapf--accumulate
)))
548 (avl-tree--root tree
)
550 (nreverse avl-tree-mapf--accumulate
)))
553 (defun avl-tree-mapcar (fun tree
&optional reverse
)
554 "Apply FUNCTION to all elements in AVL tree TREE,
555 and make a list of the results.
557 The FUNCTION is applied and the list constructed in ascending
558 order, or descending order if REVERSE is non-nil.
560 Note that if you don't care about the order in which FUNCTION is
561 applied, just that the resulting list is in the correct order,
564 (avl-tree-mapf function \\='cons tree (not reverse))
567 (nreverse (avl-tree-mapf fun
'cons tree reverse
)))
570 (defun avl-tree-first (tree)
571 "Return the first element in TREE, or nil if TREE is empty."
572 (let ((node (avl-tree--root tree
)))
574 (while (avl-tree--node-left node
)
575 (setq node
(avl-tree--node-left node
)))
576 (avl-tree--node-data node
))))
578 (defun avl-tree-last (tree)
579 "Return the last element in TREE, or nil if TREE is empty."
580 (let ((node (avl-tree--root tree
)))
582 (while (avl-tree--node-right node
)
583 (setq node
(avl-tree--node-right node
)))
584 (avl-tree--node-data node
))))
586 (defun avl-tree-copy (tree)
587 "Return a copy of the AVL tree TREE."
588 (let ((new-tree (avl-tree-create (avl-tree--cmpfun tree
))))
589 (setf (avl-tree--root new-tree
) (avl-tree--do-copy (avl-tree--root tree
)))
592 (defun avl-tree-flatten (tree)
593 "Return a sorted list containing all elements of TREE."
594 (let ((treelist nil
))
596 (lambda (node) (push (avl-tree--node-data node
) treelist
))
597 (avl-tree--root tree
) 1)
600 (defun avl-tree-size (tree)
601 "Return the number of elements in TREE."
604 (lambda (_) (setq treesize
(1+ treesize
)))
605 (avl-tree--root tree
) 0)
608 (defun avl-tree-clear (tree)
609 "Clear the AVL tree TREE."
610 (setf (avl-tree--root tree
) nil
))
613 (defun avl-tree-stack (tree &optional reverse
)
614 "Return an object that behaves like a sorted stack
615 of all elements of TREE.
617 If REVERSE is non-nil, the stack is sorted in reverse order.
618 \(See also `avl-tree-stack-pop').
620 Note that any modification to TREE *immediately* invalidates all
621 avl-tree-stacks created before the modification (in particular,
622 calling `avl-tree-stack-pop' will give unpredictable results).
624 Operations on these objects are significantly more efficient than
625 constructing a real stack with `avl-tree-flatten' and using
626 standard stack functions. As such, they can be useful in
627 implementing efficient algorithms of AVL trees. However, in cases
628 where mapping functions `avl-tree-mapc', `avl-tree-mapcar' or
629 `avl-tree-mapf' would be sufficient, it is better to use one of
631 (let ((stack (avl-tree--stack-create tree reverse
)))
632 (avl-tree--stack-repopulate stack
)
636 (defun avl-tree-stack-pop (avl-tree-stack &optional nilflag
)
637 "Pop the first element from AVL-TREE-STACK.
638 \(See also `avl-tree-stack').
640 Returns nil if the stack is empty, or NILFLAG if specified.
641 \(The latter allows an empty stack to be distinguished from
642 a null element stored in the AVL tree.)"
644 (if (not (setq node
(pop (avl-tree--stack-store avl-tree-stack
))))
647 (avl-tree--node-branch
649 (if (avl-tree--stack-reverse avl-tree-stack
) 0 1)))
650 (push next
(avl-tree--stack-store avl-tree-stack
))
651 (avl-tree--stack-repopulate avl-tree-stack
))
652 (avl-tree--node-data node
))))
655 (defun avl-tree-stack-first (avl-tree-stack &optional nilflag
)
656 "Return the first element of AVL-TREE-STACK, without removing it
659 Returns nil if the stack is empty, or NILFLAG if specified.
660 \(The latter allows an empty stack to be distinguished from
661 a null element stored in the AVL tree.)"
662 (or (car (avl-tree--stack-store avl-tree-stack
))
666 (defun avl-tree-stack-empty-p (avl-tree-stack)
667 "Return t if AVL-TREE-STACK is empty, nil otherwise."
668 (null (avl-tree--stack-store avl-tree-stack
)))
673 ;;; avl-tree.el ends here