BST - 2
BST - 2
BST-2
Prerequisites:
Understanding of recursion
Today's Checklist:
Code:
#include <iostream>
// BST Node
struct Node {
int key;
};
pre = NULL;
suc = NULL;
Java
C++ &+ DSA
DSA
while (temp1) {
suc = temp1;
temp1 = temp1->left;
else
temp1 = temp1->right;
while (temp2) {
pre = temp2;
temp2 = temp2->right;
else
temp2 = temp2->left;
return;
temp->key = item;
return temp;
* BST */
if (node == NULL)
return newNode(key);
else
return node;
Explanation:
Takes BST root, key, and pre/suc Node pointers
Initializes pre and suc to NULL
Finds predecessor (pre) and successor (suc) nodes of the given key in BST using two while loops
Takes an integer item
Creates and returns a new Node with the given item as key, and left/right pointers set to NULL
Inserts a new node with the given key into the BST
Creates a new root if the tree is empty, else recursively inserts in the left/right subtree based on key
comparison.
Java
C++ &+ DSA
DSA
Time Complexity:
findPreSuc function:
The function traverses the tree once for the predecessor and once for the successor.
insert function:
In the worst case, it involves traversing from the root to a leaf node.
Space Complexity:
The space complexity for both findPreSuc and insert functions is O(1) excluding the
recursive call stack.
Additional space is used only for the recursive call stack during function calls.
If the BST is balanced, the maximum space required for the call stack is O(log n), where n
is the number of nodes.
In the worst case, when the tree is skewed (like a linked list), the space complexity for the
call stack can be O(n).
Example 1:
Output: [5,4,6,2,null,null,7]
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.
Code:
class Solution {
public:
if(root)
Java
C++ &+ DSA
DSA
else if(key > root- >val) root- >right = deleteNode(root-- >right, key);
else{
if (!root->left || !root->right)
root->val = temp->val;
return root;
}
};
Explanation:
C++ class Solution with a deleteNode method for BST
Recursively searches for node with given key
Handles cases: no children, one child, and two children
For two children, replaces node's value with max value in left subtree
Continues recursively to delete the replaced node
Returns the modified tree.
Time Complexity:
O(h), where h is the height of the BST.
In the worst case, when the tree is skewed, the height h is equivalent to the number of
nodes, making it O(n).
Space Complexity:
O(h) for the recursive call stack.
In the worst case, when the tree is skewed, the space complexity is O(n).
Java
C++ &+ DSA
DSA
THANK
YOU !