21-binary-search-tree-2

# 21-binary-search-tree-2 - CSE 143 Lecture 21 Binary Search...

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

CSE 143 Lecture 21 Binary Search Trees, continued read 17.3 - 17.5 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 Exercise • Add a method add to the SearchTree class that adds a given integer value to the tree. Assume that the elements of the SearchTree constitute a legal binary search tree, and add the new value in the appropriate place to maintain ordering. •tree.add(49) ; 91 60 87 29 55 42 -3 overall root 49
3 An incorrect solution // Adds the given value to this BST in sorted order. public void add(int value) { add(overallRoot, value); } private void add(IntTreeNode node, int value) { if (node == null) { node = new IntTreeNode(value); } else if (node.data > value) { add(node.left, value); } else if (node.data < value) { add(node.right, value); } // else node.data == value, so // it's a duplicate (don't add) } • Why doesn't this solution work? 91 60 87 29 55 42 -3 overallRoot

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

View Full Document
4 The problem • Much like with linked lists, if we just modify what a local variable refers to, it won't change the collection. public void add(int value) { add(overallRoot, value); } private void add(IntTreeNode node, int value) { if (node == null) { node = new IntTreeNode(value); } . .. – In the linked list case, how did we actually modify the list? • by changing the front • by changing a node's next field 91 60 87 29 55 42 -3 overallRoot 49 node
5 A poor correct solution // Adds the given value to this BST in sorted order. (bad style) public void add(int value) { if (overallRoot == null) { overallRoot = new IntTreeNode(value); } else if (overallRoot.data > value) {

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.

## 21-binary-search-tree-2 - CSE 143 Lecture 21 Binary Search...

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

View Full Document
Ask a homework question - tutors are online