BST - 1
BST - 1
BST-1
Prerequisites:
Understanding of recursion
Today's Checklist:
Binary Search Tree is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key
The right subtree of a node contains only nodes with keys greater than the node’s key
The left and right subtree each must also be a binary search tree.
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If
Java
C++ &+ DSA
DSA
Example 1:
Output: [2,1,3]
Code:
class Solution {
public:
the tree.
if (root == NULL) {
return NULL;
if (root->val == val) {
return root;
subtree.
else {
};
Java
C++ &+ DSA
DSA
Explanation:
The code defines a class named Solution
The class has a public member function searchBST that takes a TreeNode* (root of a binary search
tree) and an integer val as parameters
If the current node is NULL (empty tree) or the target value is not found, the function returns NULL
If the current node's value matches the target value, the function returns the current node
If the target value is smaller than the current node's value, the function recursively calls itself with
the left subtree as the new root
If the target value is larger, the function recursively calls itself with the right subtree as the new root.
Time Complexity: O(h) in the average case, O(N) in the worst case, where h is the height of the binary
search tree and N is the number of nodes.
Space Complexity: O(h) in the average case, O(N) in the worst case, where h is the height of the binary
search tree and N is the number of nodes. This accounts for the recursion stack during the recursive calls.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after
insertion. You can return any of them.
Output: [4,2,7,1,3,5]
class Solution {
public:
return root;
};
Java
C++ &+ DSA
DSA
Explanation:
The function insertIntoBST inserts a new node with value val into a binary search tree
If the root is null, it creates a new node with value val and returns it
If the value to be inserted (val) is less than the root's value, it recursively calls the function on the left
subtree
If the value to be inserted is greater than or equal to the root's value, it recursively calls the function on
the right subtree
Finally, it returns the root of the modified binary search tree.
Time Complexity:
Space Complexity:
#include <iostream>
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
};
if (root == nullptr) {
return;
preorderTraversal(root->left);
preorderTraversal(root->right);
Java
C++ &+ DSA
DSA
Explanation:
TreeNode struct: Represents a node in a binary tree, containing data, a pointer to the left child, and a
pointer to the right child
preorderTraversal function: Performs a preorder traversal of the binary tree, printing each node's data as
it is visited
Calls preorderTraversal to print the nodes in preorder
Deletes allocated memory for proper cleanup.
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
if (root == nullptr) {
return;
inorderTraversal(root->left);
inorderTraversal(root->right);
Explanation:
The code defines a TreeNode structure to represent nodes in the Binary Search Tree (BST)
The inorderTraversal function recursively traverses the BST in inorder (left subtree, current node, right
subtree) and prints the values
The main function creates a sample BST, invokes inorderTraversal, and prints the elements in
ascending order.
Java
C++ &+ DSA
DSA
Time Complexity:
The time complexity of the inorder traversal in a Binary Search Tree is O(n), where n is the number of nodes
in the tree.
In the worst case, if the tree is skewed (all nodes have only one child), the space complexity becomes O(n).
In the average case for a balanced BST, the space complexity is O(log n), where log n is the height of a
balanced tree.
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
};
if (root == nullptr) {
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
Explanation:
Node Structure: Defines a structure for a Binary Search Tree (BST) node with integer data, left, and right
pointers
postorderTraversal Function: Recursively traverses BST in postorder (left subtree, right subtree, root),
printing node data
main Function: Creates a sample BST, performs postorder traversal, and prints the result
Memory Cleanup (Optional): Properly frees allocated memory for the sample BST in the main function.
Java
C++ &+ DSA
DSA
Time Complexity: O(n) - Linear time, as each node is visited exactly once during postorder traversal.
Space Complexity:
Recursive Stack Space: O(h), where 'h' is the height of the BST. Worst case O(n), average case O(log n).
Additional Space: O(1), constant space for variables and pointers during traversal.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two
nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to
be a descendant of itself).”
Example 1:
Output: 6
class Solution {
public:
return lowestCommonAncestor(root->right,p,q);
return lowestCommonAncestor(root->left,p,q);
return root;
};
Java
C++ &+ DSA
DSA
Explanation:
The code defines a Solution class with a function lowestCommonAncestor that finds the lowest common
ancestor of two nodes in a binary search tree
The function recursively traverses the tree, comparing values of the current node (cur) with the values of
the two given nodes (p and q)
If both nodes are on the right, the function recursively calls itself with the right subtree
If both nodes are on the left, the function recursively calls itself with the left subtree
If the current node's value is between the values of p and q, it is the lowest common ancestor, and the
function returns the current node.
Time Complexity: O(log N) on average, O(N) in the worst case (unbalanced tree).
Space Complexity: O(log N) on average, O(N) in the worst case (due to recursive call stack).
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Output: true
Code:
class Solution {
public:
};
Java
C++ &+ DSA
DSA
Explanation:
The code defines a class named Solution
It contains a private helper function isPossible to recursively check if the given root node and its
descendants form a valid binary search tree (BST) within the specified range [l, r]
The isValidBST function initializes the range with minimum and maximum values and calls the
isPossible function to determine if the binary tree rooted at root is a valid BST
The code utilizes a long long data type for the range to handle large integer values
The function returns true if the tree is a valid BST, and false otherwise.
Time Complexity:
The time complexity of the isValidBST function is O(N), where N is the number of nodes in the binary tree.
This is because the function performs a recursive traversal of each node exactly once.
Space Complexity:
The space complexity is O(H), where H is the height of the binary tree.
In the worst case, when the tree is skewed (like a linked list), the height H can be equal to the number of
nodes N, resulting in O(N) space complexity.
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
convertTree(root->left, sum);
root->val = sum;
sum-=currNodeVal;
convertTree(root->right, sum);
convertTree(root, nodeSum);
return root;
};
Explanation:
The code defines a class Solution with three member functions for converting a Binary Search Tree
(BST) to Greater Sum Tree (GST)
convertTree recursively converts the BST to GST by updating each node's value to the sum of all
greater values in the tree
getSum recursively calculates the sum of all node values in the tree
bstToGst uses getSum to get the total sum of the BST, then applies convertTree to modify the tree in-
place, and finally returns the modified root
The conversion is achieved by traversing the BST in reverse in-order (right, root, left) and updating
each node's value accordingly.
Time Complexity:
O(n) in the worst case (skewed tree), O(log(n)) in the average case for a balanced BST.
Java
C++ &+ DSA
DSA
Convert Sorted Array to Balanced BST [Leetcode-108]
Given an integer array nums where the elements are sorted in ascending order, convert it to a
Example 1:
Output: [0,-3,9,-10,null,5]
Code:
class Solution {
public:
if(nums.size()==0)return NULL;
root->left = sortedArrayToBST(leftsub);
root->right = sortedArrayToBST(rightsub);
return root;
};
Explanation:
Takes a sorted array (nums) and returns the root of a height-balanced Binary Search Tree (BST)
If the array is empty, returns NULL
If the array has only one element, creates a new TreeNode with that element and returns it
Finds the middle index of the array and creates a new TreeNode with the corresponding element as
the root
Recursively constructs left and right subtrees using subarrays split at the middle index
Assigns the left and right subtrees as the left and right children of the root, respectively
Returns the root of the constructed BST.
Java
C++ &+ DSA
DSA
Time Complexity:
The time complexity is O(N), where N is the number of elements in the input sorted array.
Each element in the array is processed once, and for each element, a constant amount of work is done.
Space Complexity:
In each recursive call, new vectors (leftsub and rightsub) are created, each containing roughly half of the
elements of the current array.
The maximum depth of the recursion is log(N) for a balanced tree, and at each level, O(N) space is used for
the vectors.
It is guaranteed that there is always possible to find a binary search tree with the given requirements for the
given test cases.
A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly
less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.
A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then
traverses Node.right.
Example 1:
Output: [8,5,10,1,7,null,12]
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
vector<int>inorder, v;
v=preorder;
sort(v.begin(), v.end());
inorder=v;
if(preorder.size()==0){return NULL;}
map<int, int>m;
m[inorder[i]]=i;
return root;
int pos=m[preorder[pst]];
int lft=pos-inst;
return root;
};
Explanation:
The code defines a Solution class with a public function bstFromPreorder that takes a vector of
integers representing the preorder traversal of a binary search tree (BST) and returns the root of the
BST
It sorts the preorder vector to get the inorder traversal, which helps in constructing the BST
It checks if the preorder vector is empty, and if so, returns NULL
It creates a map m to store the positions of elements in the inorder traversal
The formtree function recursively constructs the BST using the preorder and inorder traversals,
updating the root, left, and right subtrees accordingly
The base case of recursion is when the start position is greater than the end position or the start
position in the inorder traversal is greater than the end position, in which case it returns NULL
The constructed root is returned as the result.
Time Complexity:
Space Complexity:
Java
C++ &+ DSA
DSA
THANK
YOU !