BINARY SEARCH TREES RECURSION RECURSION To understand recursion
BINARY SEARCH TREES + RECURSION
RECURSION “To understand recursion, you must first understand recursion. ” -- Stephen Hawking • Simple definition: a function / method that calls itself. • Why? • Construction: • Base-case • Whittling-down • Comparison to Iterative (loop/stack-based) • Simple Examples: • [Factorial? ] • [Fibonacci] – make it better… • [Palindrome]
WHAT IS IT? • A data collection (like Linked. List) • • • Generic Contains a Node class (hidden from the user) Some kind of add method Some kind of find method Some kind of traversal mechanism • Some differences: • The collection will be sorted • • public class Foo<E> -changes topublic class Foo<E extends Comparable> to compare two Comparables, use. compare. To • <0 implies the first is less than the second, =0 implies they’re equal, …
VOCABULARY • • • Root Leaf Arity of tree (BST=2) Parent / Child Descendent / Ancestor Depth Sub-tree Balanced trees Trees=acyclic-directed-graph
BST STRUCTURE • Node class • • Payload Left Right Parent? (Makes remove a little easier, but is “wasted” space) • BST class • Root node • Size
SIDE-TOPIC: RECURSION • • • Simple defintion: a function that calls itself Example on board: factorial, fibonacci Example to try: palindrome checker Harder problem: Towers of Hanoi [Side-note]: Show the debugger Is it perfect? • Shorfalls… • Iterative alternatives • I’m going to have you make most methods recursive and handle them in the Node class • If you were the designer, nothing is wrong with doing it iteratively in the BST class.
ADD PSEUDO-CODE • [On board]
REMOVE PSEUDO-CODE • A little more complex • Three cases: • You have no children – simple just remove this node. • You only have one child – simple: just promote the child to your spot • You have both children – not so simple • [Draw a scenario on the board] • Find the largest descendent of your left child or the smallest descendent of your right child to promote • Which one: probably better to use the sub-tree with the most nodes (this makes us more likely to be balances) • One other special case: deleting the root.
DEGENERATE TREES • What are they? • Why are the bad? • How to fix?
- Slides: 9