Binary Search Trees

Ace your homework & exams now with Quizwiz!

Template for Tree Methods

public class IntTree { private IntTreeNode overallRoot; ... public type name(parameters) { name(overallRoot, parameters); } private type name(IntTreeNode root, parameters) { ... } }

Add a method remove to the SearchTree class that removes a given integer value from the tree, if present. Assume that the elements of the SearchTree constitute a legal binary search tree, and remove the value in such a way as to maintain ordering. • tree.remove(73); • tree.remove(29); • tree.remove(87); • tree.remove(55);

Cases for removal 1 1. a leaf: replace with null 2. a node with a left child only: replace with left child 3. a node with a right child only: replace with right child 4. a node with both children: replace with min from right

A binary tree can be defined as either:

- empty (null), or - a root node that contains: • data, • a left subtree, and • a right subtree. - (The left and/or right subtree could be empty.) each Node can have at most two children

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.

// Adds the given value to this BST in sorted order. public void add(int value) { overallRoot = add(overallRoot, value); } private IntTreeNode add(IntTreeNode root, int value) { if (root == null) { root = new IntTreeNode(value); } else if (root.data > value) { root.left = add(root.left, value); } else if (root.data < value) { root.right = add(root.right, value); } // else a duplicate return root; }

Exercise • Add a method print to the IntTree class that prints the elements of the tree, separated by spaces. - A node's left subtree should be printed before it, and its right subtree should be printed after it. - Example: tree.print(); 29 41 6 17 81 9 40 - Hint: Use Recursion

// An IntTree object represents an entire binary tree of ints. public class IntTree { private IntTreeNode overallRoot; // null for an empty tree ... public void print() { print(overallRoot); System.out.println(); // end the line of output } private void print(IntTreeNode root) { // (base case is implicitly to do nothing on null) if (root != null) { // recursive case: print left, center, right print(overallRoot.left); System.out.print(overallRoot.data + " "); print(overallRoot.right); } } }

IntTreeNode class

// An IntTreeNode object is one node in a binary tree of ints. public class IntTreeNode { public int data; // data stored at this node public IntTreeNode left; // reference to left subtree public IntTreeNode right; // reference to right subtree // Constructs a leaf node with the given data. public IntTreeNode(int data) { this(data, null, null); } // Constructs a branch node with the given data and links. public IntTreeNode(int data, IntTreeNode left, IntTreeNode right) { this.data = data; this.left = left; this.right = right; } }

Remove Solution

// Removes the given value from this BST, if it exists. public void remove(int value) { overallRoot = remove(overallRoot, value); } private IntTreeNode remove(IntTreeNode root, int value) { if (root == null) { return null; } else if (root.data > value) { root.left = remove(root.left, value); } else if (root.data < value) { root.right = remove(root.right, value); } else { // root.data == value; remove this node if (root.right == null) { return root.left; // no R child; replace w/ L } else if (root.left == null) { return root.right; // no L child; replace w/ R } else { // both children; replace w/ min from R root.data = getMin(root.right); root.right = remove(root.right, root.data); } } return root; }

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

// 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); } }

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. - the elements are comparable • BSTs store their elements in sorted order, which is helpful for searching/sorting tasks. • Behavior - create tree - search - insert - traverse

Applying x = change(x)

• Methods that modify a tree should have the following pattern: - input (parameter):old state of the node - output (return): new state of the node • In order to actually change the tree, you must reassign: root = change(root, parameters); root.left = change(root.left, parameters); root.right = change(root.right, parameters);

Binary Tree Terminology

• Node: an object containing a data value and left/right children • Root: topmost node of a tree • Leaf: a node that has no children • Branch: any internal node; neither the root nor a leaf • Parent: a node that refers to this one • Child: a node that this node refers to • Sibling: a node with a common parent • Subtree: the tree of nodes reachable to the left/right from the current node • Height: length of the longest path from the root to any node • Level or depth: length of the path from a root to a given node • Full tree: one where every branch has 2 children

Traversal Example --------17 -------/--\ -----41----9 ----/

• Pre-order: 17 41 29 6 9 81 40 • In-order: 29 41 6 17 81 9 40 • Post-order: 29 6 41 81 40 9 17

x = change(x);

• String methods that modify a string actually return a new one. - If we want to modify a string variable, we must re-assign it. String s = "hello"; s.toUpperCase(); System.out.println(s); // hello s = s.toUpperCase(); System.out.println(s); // HELLO - We call this general algorithmic pattern x = change(x); - We will use this approach when writing methods that modify the structure of a binary tree.

Searching BSTs

• The BSTs below contain the same elements. - What orders are "better" for searching? the shortest in height tree

Traversal trick

• To quickly generate a traversal: - Trace a path around the tree. starting from left - As you pass a node on the proper side, process it. • pre-order: left side • in-order: bottom • post-order: right side

Traversals

• Traversal: An examination of the elements of a tree. - A pattern used in many tree algorithms and methods • Common orderings for traversals: - Pre-order: process root node, then its left/right subtrees - In-order: process left subtree, then root node, then right - Post-order: process left/right subtrees, then root node

Trees

• Tree: A directed, acyclic structure of linked nodes. - directed : Has one-way links between nodes. - acyclic : No path wraps back around to the same node twice. - binary tree: One where each node has at most two children

Trees in Computer Science

• folders/files on a computer • family genealogy; organizational charts • AI: decision trees • compilers: parse tree - a = (b + c) * d;

final

be able to draw a BST and then traverse it

Add a method getMin to the SearchTree class that returns the minimum integer value from the tree. Assume that the elements of the SearchTree constitute a legal binary search tree. Throw a NoSuchElementException if the tree is empty. int min = tree.getMin(); // -3

go left // Returns the minimum value from this BST. // Throws a NoSuchElementException if the tree is empty. public int getMin() { if (overallRoot == null) { throw new NoSuchElementException(); } return getMin(overallRoot); } private int getMin(IntTreeNode root) { if (root.left == null) { return root.data; } else { return getMin(root.left); } }

tree example pic on phone

preorder:(left) 42,15,27,9,48,9,86,125,3,39 post order (right): 48,27,15,5,12,86,39,3,9,42 in order: (bottom): 15,48,27,42,86,5,12,9,3,39

A TreeNode for Integers

• A basic tree node object stores data and refers to left/right • Multiple nodes can be linked together into a larger tree

Trees and balance

• Balanced Tree: One whose subtrees differ in height by at most 1 and are themselves balanced. - A balanced tree of N nodes has a height of ~ log2 N. - A very unbalanced tree can have a height close to N. - The runtime of adding to / searching a BST is closely related to height. - Some tree collections (e.g. TreeSet) contain code to balance themselves as new nodes are added.


Related study sets

ACSM Guidelines Chapter 6 - General Principles of Exercise Prescription

View Set