Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Search Trees CSE 331 Section 2 James Daly.

Similar presentations

Presentation on theme: "Binary Search Trees CSE 331 Section 2 James Daly."— Presentation transcript:

1 Binary Search Trees CSE 331 Section 2 James Daly

2 Homework 1 Homework 1 is due on today Leave on the front table

3 Review: SampleTrees … T1T1 T2T2 TkTk

4 Review: Terminology Parent Child Ancestor Descendent Root Leaf Internal A BC D

5 Review: Terminology Path Depth Height A BC D

6 Review: Binary Tree Every node has at most 2 children Left and right child Variation: n-ary trees have at most n children

7 Binary Search Tree For every node Left descendents smaller (l ≤ k) Right descendents bigger (r ≥ k) k k

8 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

9 Eval Tree *++abc-d3 Pre-order: * +ab +c -d3 In-order: a + b*c + d – 3 Post-order: ab+ cd3- + *

10 Search Tree

11 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

12 Find(t, x) If (t = null) null Else If (x < Find(t.left, x) Else If (x > Find(t.right, x) Else t ?

13 FindMin(t) [Recursive] If (t.left != null) t Else FindMin(t.left)

14 Insert(t, x) If (t = null) t = new Node(x) Else If (x < Insert(t.left, x) Else If (x > Insert(t.right, x) Construct a BST for 5, 3, 9, 2

15 Delete: 1 st Case Leaf Node

16 Delete: 2 nd Case One Child

17 Delete: 3 rd Case Two children Swap with least successor (or greatest predecessor) Then delete from the right (or left) subtree

18 Delete: 3 rd Case



21 Next Time Balanced binary search trees AVL trees Maybe Red-Black trees

Download ppt "Binary Search Trees CSE 331 Section 2 James Daly."

Similar presentations

Ads by Google