Permalink
Browse files

added count test case

modified algorithm to count whil modifying tree
  • Loading branch information...
1 parent 71dc174 commit 888300f73157b34738a3642f02ab91b6f2f29878 @sake committed Feb 18, 2010
Showing with 25 additions and 16 deletions.
  1. +10 −16 src/redblack.lisp
  2. +15 −0 test/testcases.lisp
View
@@ -140,19 +140,7 @@
(defmethod treemap-count ((tree redblack-tree-map))
- "Quick and dirty iterate function. TODO: replace"
- (let ((num 0))
- (labels ((recurse-node (node)
- (if node
- (progn
- ;; recurse to the left
- (recurse-node (rb-left node))
- ;; count this node
- (incf num)
- ;; recurse to the right
- (recurse-node (rb-right node))))))
- (recurse-node (data tree)))
- num))
+ (num-elements tree))
(defmethod map-tree ((function function) (tree redblack-tree-map))
@@ -210,7 +198,9 @@
(progn
(setf ret-val (rb-value
(setf (data tree) (rb-make-node key value))))
- (setf ret-status t))
+ (setf ret-status t)
+ ;; update node count
+ (incf (num-elements tree)))
;; else: tree not empty
(let ((head (rb-make-empty-node))
@@ -231,7 +221,9 @@
(cond ((not q)
;; insert new node
(setf (rb-child p dir)
- (setf q (rb-make-node key))))
+ (setf q (rb-make-node key)))
+ ;; update node count
+ (incf (num-elements tree)))
;; color flip
((and (is-red (rb-left q))
@@ -349,7 +341,9 @@
(if (eq (rb-right p) q) 'right 'left))
(rb-child q
(if (not (rb-left q)) 'right 'left)))
- (setf node-deleted t)))
+ (setf node-deleted t)
+ ;; reduce node count
+ (decf (num-elements tree))))
;; update root and make it black
(setf (data tree) (rb-right head))
(if (data tree)
View
@@ -71,3 +71,18 @@
;; test if all elements are now in first tree
(loop for i from 0 to 1000 do
(is (= i (get-tree-entry (first tree-list) i) i))))))
+
+(test count-tree
+ (let ((tree (make-tree :type :red-black))) ;; nothing can go wrong here
+ ;; insert values into tree
+ (loop for i from 0 to 100 do
+ (progn
+ (is (= (treemap-count tree) i))
+ (setf (get-tree-entry tree i) i)
+ (is (= (treemap-count tree) (1+ i)))))
+ ;; delete values
+ (loop for i from 100 downto 0 do
+ (progn
+ (is (= (treemap-count tree) (1+ i)))
+ (del-tree-entry tree i)
+ (is (= (treemap-count tree) i))))))

0 comments on commit 888300f

Please sign in to comment.