Implement binary search tree with parent pointer

A binary search tree is a type of ordered binary tree, where the left child has a value smaller than its parent, and the right child has a value greater than or equal to its parent. In a binary search tree, a node has two references, the left child and the right child. A binary search tree with a parent pointer is a variation of a binary search tree – a node has an additional reference to its parent node. Normally a binary search tree’s operations start from the root node. With additional parent pointers, the operations can start from any given node, which improves performance in some cases.

Binary search tree with parent pointer

Table of Content


Define classes

A TreeNode class in a binary search tree with a parent pointer has 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. parent is the reference to the parent node.

After you define TreeNode, you can define the BinarySearchTree class. It has one attribute, 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 in a binary search tree with parent

To insert a value in a binary search tree, you have to find the right spot, which satisfies the rule of the binary search tree – the parent’s value is larger than the left child’ value, and the right child’s value is larger than the parent’s value.

From root, you compare the input value with each node’s data. If the input value is larger than the node’s data, you move to its right child. Otherwise, move to its left child. You also keep track of the previously visited node and save it in a variable named parent or previous.

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

Java

JavaScript

Python


Delete by key

Deleting a node in a binary search tree with a parent pointer is a little more complicated. First, you find the node with the data that matches the key. Then find its successor. The in-order successor in a binary search tree is the right child’s leftmost descendent.  After you replace the deleted node with the successor, you point the successor’s parent to the old parent.

Java

JavaScript

Python


Free download

Download BinarySearchTreeWithParent.java
Download BinarySearchTreeWithParent.js
Download BinarySearchTreeWithParent.py
Binary tree

Comments are closed