Implement binary search tree with parent pointer

In a binary search tree, a node has two references, left child and right child. A binary search tree with parent is an 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 improve performance.

Binary search tree with parent pointer

Table of Content


Define classes

A TreeNode class in binary search tree with parent 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 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

In order to insert a value in a binary search tree, you have to find the right spot. 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 the previous visited node and save it in a variable.

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 parent is a little more complicated. First you find the node with the data matches with the key. Then find its successor. The inorder successor in a binary search tree is the right child’s left most 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