# What is binary search tree in java

In a BST, each node stores some information including a unique key value and perhaps some associated data. A binary search tree can be used to store any objects that implement the Comparable interface i. A BST can also be used to store Comparable objects plus some associated data. As an example, let's delete 16 from the BST just formed:. Note that lookup always follows a path from the root down towards a leaf.

In these notes, we will assume that duplicates are not allowed. The keySet method returns a Set containing all the keys currently in the map. In general, we'd like what is binary search tree in java know how much time is required for lookup as a function of the number of values stored in the tree. A BST can also be used to store Comparable objects plus some associated data. This depends on the "shape" of the tree.

This example used a set of String. Using which kind of traversal pre-order, post-order, in-order, or level-order visits the nodes of a BST in sorted order? Without it, the program would look for "words" separated by spaces, considering "details" and "details. Once the value is found, we copy it into node nthen we recursively delete that value from n 's right subtree.

See the documentation for Scanner and Pattern for more details. The class that most closely matches the outline above, in which the nodes contain only keys and no other data, is called TreeSet. When the node to delete is a leaf, we what is binary search tree in java to remove it from the BST by setting the appropriate child pointer of its parent to null or by setting root to null if the node to be deleted is the root and it has no children. We'll arbitrarily decide to use the smallest value in the right subtree.

In the worst case, it goes all the way to a leaf. The method get key returns the value associated with key or null if there is no such value. Both keys and values can be null. Note that lookup always follows a path from the root down towards a leaf.

If a tree is not a BST, say why. So the worst-case time is proportional to the height of the tree just like for lookup and insert. Which of the following binary trees are BSTs? An important special kind of binary tree is the binary search tree BST. In the worst case a "linear" tree this is O Nwhere N is the number of nodes in the tree.

We'll arbitrarily decide to use the smallest value in the right subtree. However, when we use big-O notation, we just say that the height of a full tree with N nodes is O log N -- we drop the "2" subscript, because log 2 N is proportional to log k N for any constant k, i. We will also assume that null is not a valid key value i.

Where should a new item go in a BST? If you want to associate data with each key, use interface Map and the corresponding class TreeMap. Here is an outline of the code for the delete method. If you don't put it there then you won't find it later. Here's the final version of the delete method:.