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

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

View Full Document Right Arrow Icon
CSE 143 Lecture 21 Binary Search Trees, continued read 17.3 - 17.5 slides created by Marty Stepp http://www.cs.washington.edu/143/
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 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
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
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
Background image of page 4
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) {
Background image of page 5

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

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

Page1 / 16

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 Right Arrow Icon
Ask a homework question - tutors are online