--- a/BinaryTree.st Wed Oct 01 20:20:35 2008 +0200
+++ b/BinaryTree.st Thu Oct 09 11:25:06 2008 +0200
@@ -115,6 +115,46 @@
Transcript show:'Time to remove selectors from BinaryTree: '; show:t2; showCR:'ms'.
[exEnd]
+ A functional example of a UCB-CS61A lecture's example.
+ The task is to extract all values within a given range (min..max) from
+ a binary tree.
+ The range 'function' below does this; given a binary tree, a min and max value,
+ range(bst, min, max)
+ returns an array of all values which are within that range.
+ Only the relevant branches of the binary tree are to be visited, of course.
+ [exBegin]
+ |t rangeNode range|
+
+ t := BinaryTree new.
+ t add:54; add:37; add:19; add:45; add:80; add:65; add:91; add:57.
+
+ rangeNode := [:node :min :max |
+ |nodeValue leftTree rightTree left right middle|
+
+ leftTree := node leftSubtree.
+ rightTree := node rightSubtree.
+ nodeValue := node data.
+
+ left := (leftTree notNil and:[nodeValue > min])
+ ifTrue:[ rangeNode value:leftTree value:min value:max ]
+ ifFalse:[ #() ].
+
+ right := (rightTree notNil and:[nodeValue < max])
+ ifTrue:[ rangeNode value:rightTree value:min value:max ]
+ ifFalse:[ #() ].
+
+ middle := (nodeValue between:min and:max)
+ ifTrue:[ (Array with:nodeValue) ]
+ ifFalse:[ #() ].
+
+ left, middle, right
+ ].
+ range := [:tree :min :max |
+ rangeNode value:tree rootNode value:min value:max
+ ].
+ range value:t value:30 value:60.
+ [exEnd]
+
"
! !
@@ -134,6 +174,10 @@
!BinaryTree methodsFor:'accessing'!
+rootNode
+ ^ treeRoot
+!
+
sortBlock:something
"set the sort block.
This is allowed only before any elements are stored in the tree"
@@ -808,5 +852,5 @@
!BinaryTree class methodsFor:'documentation'!
version
- ^ '$Header: /cvs/stx/stx/libbasic2/BinaryTree.st,v 1.6 2007-12-06 21:51:49 stefan Exp $'
+ ^ '$Header: /cvs/stx/stx/libbasic2/BinaryTree.st,v 1.7 2008-10-09 09:25:06 cg Exp $'
! !