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>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 428136957

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 < t.data) Find(t.left, x) Else If (x > t.data) Find(t.right, x) Else t 4 3 2 8 69 57 7?

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 < t.data) Insert(t.left, x) Else If (x > t.data) Insert(t.right, x) 5 39 2 Construct a BST for 5, 3, 9, 2

15 Delete: 1 st Case Leaf Node 6 57 6 5

16 Delete: 2 nd Case One Child 6788 7

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 428136957

19 528136947

20 528136947

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