{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

20-binary_search_tree

# 20-binary_search_tree - CSE143 Lecture20 BinarySearchTrees...

This preview shows pages 1–8. Sign up to view the full content.

CSE 143 Lecture 20 Binary Search Trees  read 17.3 slides created by Marty Stepp http://www.cs.washington.edu/143/

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Binary search trees binary search tree  ("BST"): a binary tree that is either: empty ( null ), or a root node R such that: every element of R's left subtree contains data "less than" R's data, every element of R's right subtree contains data "greater than" R's, R's left and right subtrees are also binary search trees. BSTs store their elements in sorted order, which is helpful for searching/sorting tasks. 91 60 87 29 55 42 -3 overall root
3 Exercise Which of the trees shown are legal binary search trees? x k q g m e b 18 10 11 5 8 4 2 7 20 18 42 -7 -1 -5 21.3 8.1 9.6 1.9 7.2

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 Searching a BST Describe an algorithm for searching the tree below for the value  31. Then search for the value 6. What is the maximum number of nodes you would need to examine to perform any search? 12 18 7 4 15 overall root -2 16 13 35 31 22 58 19 87 40
5 Exercise Convert the  IntTree  class into a  SearchTree  class. The elements of the tree will constitute a legal binary search tree. Add a method  contains  to the  SearchTree  class that  searches the tree for a given integer, returning  true  if found. If a  SearchTree  variable  tree  referred to the tree below, the  following calls would have these results: tree.contains(29)     true tree.contains(55)     true tree.contains(63)     false tree.contains(35)     false 91 60 87 29 55 42 -3 overall root

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
6 Exercise solution // Returns whether this tree contains the given integer. public boolean contains(int value) { return contains(overallRoot, value); } private boolean contains(IntTreeNode root, int value) { if (root == null) { return false; } else if (root.data == value) { return true; } else if (root.data > value) { return contains(root.left, value); } else { // root.data < value return contains(root.right, value); } }
7 Adding to a BST Suppose we want to add the value 14 to the BST below.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 22

20-binary_search_tree - CSE143 Lecture20 BinarySearchTrees...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online