Implement binary search tree

binary search tree is an ordered binary tree. The left subtree contains nodes whose keys are less than the node’s key value, while the right subtree contains nodes whose keys are greater than or equal to the node’s key value. Moreover, both subtrees are also binary search trees. A binary search tree can retrieve data efficiently.

Binary search tree with parent pointer

Table of Content


Define classes

First, define a TreeNode class. TreeNode class in binary search tree is the same as a regular binary tree. It has three attributes, data, left and right. data is the data stored in this node. Its data type can be anything such as Integer, String or Object. left is the left child. right is the right child. Their data type is TreeNode.

After you define TreeNode, you can define BinarySearchTree class. It has one attribute, root. Most tree operation start from root.

Please note, in Java, BinarySearchTree’s generic data type extends Comparable interface, so that you can compare data in insertion, deletion and search operations.

Java

JavaScript

Python


Insert

To insert a value to a binary search tree, you have to find the place to insert to satisfy the rules. Start from root, you compare the input value with each node’s data. If the input is larger than the node’s data, you move to the right child. Otherwise move to the left child, until the node’s left or right child is null. Then you can add the new node with the input value as the left or right child.

Java

JavaScript

Python


Delete by key

To delete a node in a binary search tree, you promote the inorder successor of deleted node as the replacement. The inorder successor is the right child’s left most descendent. If right child is null, promote left child.

Since you follow the path based on the comparison of node’s data with the input key, the time complexity is O(h), h is the height of the tree.

Java

JavaScript

Python


Depth first search

There are two ways to search, Depth first search and Breadth first search.

Depth first search (DFS) starts from root, and explores the child nodes as far as possible before backtracking. DFS is usually implemented with recursion or a stack.

Java

JavaScript

Python


Breadth first search

Breath First Search (BFS) starts from root, and explores all its children before going to the next level. BFS is usually implemented with a queue.

Both DFS and BFS in binary search tree has time complexity of O(h). The search doesn’t need to go through all the nodes in the tree. It follows the path based on the comparison of node’s data with the input key.

Java

JavaScript

Python


Free download

Download BinarySearchTree.java
Download BinarySearchTree.js
Download BinarySearchTree.py
Binary tree
Binary search tree with parent

Comments are closed