The binary search tree with parent is the extension of the binary search tree. In a binary search tree, the node has two references, the left child and the right child. Operations normally start from the root node. Add another reference to the parent, the operations don’t have to start from the root node anymore.

Binary search tree with parent pointer

Table of Content

What is the benefit of adding a parent pointer in a node of a binary tree?

Normally a binary tree’s operation starts from the root. If you add a parent pointer in a node, The action can start from the current node. It can go up or down the tree. This makes the search more efficient. However, adding the parent reference needs more work in insertion or deletion.


Map of binary tree implementations

Part 1 – Binary tree implementation
Part 2 – Binary search tree implementation

you are here

Part 3 – Binary search tree with parent pointer


Define classes

As its name says, the TreeNode in binary search tree with parent adds one more attribute to the regular binary tree node, parent. So there are four attributes, data, left, right, and parent. data is the data stored in this node. left is the reference to the left child. right is the reference to the right child. The parent is a reference to the parent node.

After we define TreeNode, we can define the BinarySearchTree class. It has one attribute, root. It is the node from where most tree operations start.

Please note, since a binary search tree is ordered, in Java, BinarySearchTree’s generic data type extends the Comparable interface, so that we can compare data in insert, delete, or search operations.

Java

JavaScript

Python


Binary search tree with parent method – Insert

To insert a value into a binary search tree, we have to find the right spot. From the root, we compare the input value with each node’s data. If the value is larger than the node’s data, we move to its right child. Otherwise, move to its left child, Meanwhile, we keep track of the previously visited node and save it in a variable parent.

When we reach the node whose left or right child is null, we can add the new node with the input value as left or right child. Then, add a reference to the parent for this new node.

Java

JavaScript

Python

Doodle

Binary search tree with parent insert


Delete by key

Deleting a node in a binary search tree with a parent is similar to deleting a node in a binary search tree. The first thing is to find the node with the data that matches the key. Then find its successor. In addition, we have to remember the parent of the deleted node and point the successor’s parent to the old parent.

Java

JavaScript

Python


Free download

Download binary search tree with parent in Java, JavaScript and Python
Data structures introduction PDF