Data Science/Data Structure & Algorithm
[Data Structure] BST Parent Node Pointers, and Recursion
Chan Lee
2025. 4. 23. 05:25
Parent Pointers
A BST implementation often includes a parent pointer inside each node.
A balnaced BST, such as an AVL tree or red-black tree, may utilize the parent pointer to traverse up the tree from a particular node to find a node's parent, grandparent, or siblings.
Balanced Binary Tree - GeeksforGeeks
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
www.geeksforgeeks.org
// BST Insert with nodes containing parent pointers pseudocode
BSTInsert(tree, node) {
if (tree⇢root == null) {
tree⇢root = node
node⇢parent = null
return
}
cur = tree⇢root
while (cur != null) {
if (node⇢key < cur⇢key) {
if (cur⇢left == null) {
cur⇢left = node
node⇢parent = cur
cur = null
}
else
cur = cur⇢left
}
else {
if (cur⇢right == null) {
cur⇢right = node
node⇢parent = cur
cur = null
}
else
cur = cur⇢right
}
}
}
// BST Replace Pseudocode
BSTReplaceChild(parent, currentChild, newChild) {
if (parent⇢left != currentChild &&
parent⇢right != currentChild)
return false
if (parent⇢left == currentChild)
parent⇢left = newChild
else
parent⇢right = newChild
if (newChild != null)
newChild⇢parent = parent
return true
}
// BST Remove Key and Remove Node Pseudocode
BSTRemoveKey(tree, key) {
node = BSTSearch(tree, key)
BSTRemoveNode(tree, node)
}
BSTRemoveNode(tree, node) {
if (node == null)
return
// Case 1: Internal node with 2 children
if (node⇢left != null && node⇢right != null) {
// Find successor
succNode = node⇢right
while (succNode⇢left)
succNode = succNode⇢left
// Copy value/data from succNode to node
node = Copy succNode
// Recursively remove succNode
BSTRemoveNode(tree, succNode)
}
// Case 2: Root node (with 1 or 0 children)
else if (node == tree⇢root) {
if (node⇢left != null)
tree⇢root = node⇢left
else
tree⇢root = node⇢right
// Make sure the new root, if non-null, has a null parent
if (tree⇢root != null)
tree⇢root⇢parent = null
}
// Case 3: Internal with left child only
else if (node⇢left != null)
BSTReplaceChild(node⇢parent, node, node⇢left)
// Case 4: Internal with right child only OR leaf
else
BSTReplaceChild(node⇢parent, node, node⇢right)
}
Notice that the case for a root node with 2 children is covered in Case 1: Internal Node w/ 2 Children.