18-binary_search_tree

18-binary_search_tree - CSE 143 Lecture 18 Binary Search...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CSE 143 Lecture 18 Binary Search Trees slides created by Marty Stepp http://www.cs.washington.edu/143/ 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
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 3 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 4 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
Background image of page 2
3 5 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); } } 6 Adding to a BST • Suppose we want to add the value 14 to the BST below. – Where should the new node be added? • Where would we add the value 3?
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 09/29/2010 for the course CSE 143 taught by Professor Sr during the Spring '08 term at University of Washington.

Page1 / 11

18-binary_search_tree - CSE 143 Lecture 18 Binary Search...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online