0
0
DSA C++programming~30 mins

BST Inorder Predecessor in DSA C++ - Build from Scratch

Choose your learning style9 modes available
BST Inorder Predecessor
📖 Scenario: You are working with a Binary Search Tree (BST) that stores unique integer values. You want to find the inorder predecessor of a given node value. The inorder predecessor of a node is the node with the largest value smaller than the given node's value.This is useful in many real-world applications like database indexing or navigation systems where you want to find the closest smaller key.
🎯 Goal: Build a program that creates a BST, sets a target value, finds the inorder predecessor of that target value in the BST, and prints the predecessor's value or -1 if no predecessor exists.
📋 What You'll Learn
Create a BST by inserting nodes with these exact values in order: 20, 10, 30, 5, 15, 25, 35
Create an integer variable target with the value 15
Implement a function inorderPredecessor that takes the BST root and target and returns the inorder predecessor value or -1 if none
Print the inorder predecessor value
💡 Why This Matters
🌍 Real World
Finding the inorder predecessor is useful in database indexing, memory management, and navigation systems where you need to find the closest smaller key or value.
💼 Career
Understanding BST operations like inorder predecessor is important for software engineers working on search algorithms, data storage, and optimization problems.
Progress0 / 4 steps
1
Create the BST with given nodes
Create a struct Node with int val, Node* left, and Node* right. Then create a function insertNode that inserts a value into the BST. Finally, create a BST by inserting nodes with these exact values in order: 20, 10, 30, 5, 15, 25, 35. Store the root in a variable called root.
DSA C++
Hint

Start by defining the Node struct with value and pointers. Then write insertNode to place values correctly in BST. Insert nodes one by one to build the tree.

2
Set the target value
Create an integer variable called target and set it to 15.
DSA C++
Hint

Just create an integer variable named target and assign it the value 15.

3
Implement the inorder predecessor function
Implement a function called inorderPredecessor that takes Node* root and int target as parameters and returns an int. This function should find and return the inorder predecessor value of the target in the BST. If no predecessor exists, return -1. Use the BST property to find the predecessor efficiently.
DSA C++
Hint

Use a pointer predecessor to track the last node smaller than target. Traverse the tree starting from root. If current node's value is less than target, update predecessor and go right. Otherwise, go left. Return the predecessor's value or -1 if none.

4
Print the inorder predecessor
Use cout to print the value returned by inorderPredecessor(root, target).
DSA C++
Hint

Use cout to print the value returned by inorderPredecessor(root, target). The expected output is the predecessor value or -1 if none.