Binary Search Trees CSE 331 Section 2 James Daly
Homework 1 Homework 1 is due on today Leave on the front table
Review: SampleTrees … T1T1 T2T2 TkTk
Review: Terminology Parent Child Ancestor Descendent Root Leaf Internal A BC D
Review: Terminology Path Depth Height A BC D
Review: Binary Tree Every node has at most 2 children Left and right child Variation: n-ary trees have at most n children
Binary Search Tree For every node Left descendents smaller (l ≤ k) Right descendents bigger (r ≥ k) k <k>k
Traversal Three types Pre-order Visit the parent before either of its children In-order Visit the left children before the parent Visit the right children after Post-order Visit the children before the parent
Eval Tree *++abc-d3 Pre-order: * +ab +c -d3 In-order: a + b*c + d – 3 Post-order: ab+ cd3- + *
Search Tree
All keys in left subtree <= root All keys in right subtree >= root In-order traversal => non-decreasing list Tree-sort O(n log n) build time for balanced trees O(n) time to traverse tree Can define functions to find particular items or the largest or smallest item
Find(t, x) If (t = null) null Else If (x < t.data) Find(t.left, x) Else If (x > t.data) Find(t.right, x) Else t ?
FindMin(t) [Recursive] If (t.left != null) t Else FindMin(t.left)
Insert(t, x) If (t = null) t = new Node(x) Else If (x < t.data) Insert(t.left, x) Else If (x > t.data) Insert(t.right, x) Construct a BST for 5, 3, 9, 2
Delete: 1 st Case Leaf Node
Delete: 2 nd Case One Child
Delete: 3 rd Case Two children Swap with least successor (or greatest predecessor) Then delete from the right (or left) subtree
Delete: 3 rd Case
Next Time Balanced binary search trees AVL trees Maybe Red-Black trees