Binary Search Trees CSE 331 Section 2 James Daly
Binary Search Trees
CSE 331Section 2James Daly
Homework 1
• Homework 1 is due on today• Leave on the front table
Review: SampleTrees
…T1 T2 Tk
Review: Terminology
• Parent• Child• Ancestor• Descendent• Root• Leaf• Internal
A
B C
D
Review: Terminology
• Path• Depth• Height
A
B C
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
*
+ +
a b c -
d 3
Pre-order: * +ab +c -d3In-order: a + b*c + d – 3Post-order: ab+ cd3- + *
Search Tree
4
2 8
1 3 6 9
5 7
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)
Elset
4
3
2
8
6 9
5 7
7?
FindMin(t) [Recursive]
If (t.left != null)t
ElseFindMin(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)
5
3 9
2
Construct a BST for 5, 3, 9, 2
Delete: 1st Case
• Leaf Node
6
5 7
6
5
Delete: 2nd Case
• One Child
6
7
88
7
Delete: 3rd Case
• Two children• Swap with least successor (or greatest
predecessor)• Then delete from the right (or left) subtree
Delete: 3rd Case
4
2 8
1 3 6 9
5 7
Delete: 3rd Case
5
2 8
1 3 6 9
4 7
Delete: 3rd Case
5
2 8
1 3 6 9
4 7
Next Time
• Balanced binary search trees• AVL trees• Maybe Red-Black trees