Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views206 pages

Striver A2z CPP Part 3

The document provides a comprehensive guide on binary trees, including their representation and traversal methods in C++, Java, and iterative approaches. It covers various traversal techniques such as inorder, preorder, postorder, level order, and spiral traversal, with accompanying code examples and explanations. Each section includes code snippets demonstrating the construction of binary trees and the application of different traversal methods.

Uploaded by

yashamhm19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views206 pages

Striver A2z CPP Part 3

The document provides a comprehensive guide on binary trees, including their representation and traversal methods in C++, Java, and iterative approaches. It covers various traversal techniques such as inorder, preorder, postorder, level order, and spiral traversal, with accompanying code examples and explanations. Each section includes code snippets demonstrating the construction of binary trees and the application of different traversal methods.

Uploaded by

yashamhm19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 206

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Step 13 : Binary Trees

PROBLEM:261

Question: Introduction to Trees

� Introduction to Trees in C++

cpp

#include <iostream>

using namespace std;

// Node structure

struct Node {

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Inorder traversal (Left, Root, Right)

void inorder(Node* root) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (root == nullptr) return;

inorder(root->left);

cout << root->data << " ";

inorder(root->right);

int main() {

// Creating a simple binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

cout << "Inorder Traversal: ";

inorder(root);

return 0;

� Code Explanation :

1. We define a Node structure with integer data and pointers to left and right children.
2. The inorder() function recursively visits the left subtree, root, then right subtree.
3. In main(), we manually build a small binary tree with 4 nodes.
4. We print the tree using inorder traversal, which displays the nodes in sorted-like
order for BSTs.

PROBLEM:262

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question: Binary Tree Representation in C++

� Binary Tree Representation in C++

cpp

#include <iostream>

using namespace std;

// Definition of a binary tree node

class Node {

public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Function to print inorder traversal

void inorderTraversal(Node* root) {

if (root == nullptr) return;

inorderTraversal(root->left);

cout << root->data << " ";

inorderTraversal(root->right);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

// Building a binary tree manually

Node* root = new Node(10);

root->left = new Node(20);

root->right = new Node(30);

root->left->left = new Node(40);

root->left->right = new Node(50);

cout << "Inorder Traversal of Binary Tree: ";

inorderTraversal(root);

return 0;

� Code Explanation :

1. A Node class holds data, left, and right pointers to represent a binary tree node.
2. The tree is built manually in main() using dynamic memory allocation.
3. inorderTraversal() recursively prints left subtree, current node, and right subtree.
4. This structure allows representing any binary tree by linking nodes appropriately.

PROBLEM:263

Question: Binary Tree Representation in Java

Binary Tree Representation in Java

// Definition of the binary tree node

cpp

class Node {

int data;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node left, right;

Node(int val) {

data = val;

left = right = null;

public class BinaryTree {

// Inorder traversal: Left, Root, Right

static void inorder(Node root) {

if (root == null) return;

inorder(root.left);

System.out.print(root.data + " ");

inorder(root.right);

public static void main(String[] args) {

// Creating the binary tree

Node root = new Node(10);

root.left = new Node(20);

root.right = new Node(30);

root.left.left = new Node(40);

root.left.right = new Node(50);

System.out.print("Inorder Traversal: ");

inorder(root);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

Code Explanation (in 4 lines):

1. A Node class is defined with data, left, and right to represent each binary
tree node.
2. In main(), we create a tree manually by assigning child nodes.
3. The inorder() method recursively traverses the left subtree, prints root,
then right subtree.
4. The structure supports dynamic creation and traversal of binary trees in
Java.

PROBLEM:264
Question: Binary Tree Traversals in Binary Tree

Binary Tree Traversals in C++

cpp

Binary Tree traversals are ways to visit all the nodes in a tree. The three common
types are:

1. Inorder (Left, Root, Right)


2. Preorder (Root, Left, Right)
3. Postorder (Left, Right, Root)

Here's C++ code showing all three:

cpp

#include <iostream>

using namespace std;

// Definition of a nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

};

// Inorder Traversalvoid inorder(Node* root) {

if (root == nullptr) return;

inorder(root->left);

cout << root->data << " ";

inorder(root->right);

// Preorder Traversalvoid preorder(Node* root) {

if (root == nullptr) return;

cout << root->data << " ";

preorder(root->left);

preorder(root->right);

// Postorder Traversalvoid postorder(Node* root) {

if (root == nullptr) return;

postorder(root->left);

postorder(root->right);

cout << root->data << " ";

int main() {

// Creating the binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Performing all three traversals

cout << "Inorder Traversal: ";

inorder(root);

cout << "\nPreorder Traversal: ";

preorder(root);

cout << "\nPostorder Traversal: ";

postorder(root);

return 0;

� Code Explanation (in 4 lines):

1. We define a Node class to represent each element of the binary tree.


2. In main(), we manually construct a small binary tree with 5 nodes.
3. Each traversal function uses recursion to visit nodes in a specific order.
4. We call all three functions to print Inorder, Preorder, and Postorder outputs.

PROBLEM:265
Question: Preorder Traversal of Binary Tree

� Preorder Traversal of a Binary Tree in C++

Preorder traversal follows the order: Root → Left → Right.

cpp

#include <iostream>

using namespace std;

// Definition of a binary tree nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


data = val;

left = right = nullptr;

};

// Preorder traversal functionvoid preorder(Node* root) {

if (root == nullptr) return;

cout << root->data << " ";

preorder(root->left);

preorder(root->right);

int main() {

// Creating a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Preorder Traversal: ";

preorder(root);

return 0;

� Code Explanation (in 4 lines):

1. A Node class represents each element of the binary tree.


2. The preorder() function prints root, then recursively visits left and right subtrees.
3. We manually build a binary tree in main() with 5 nodes
4. Calling preorder(root) prints nodes in Preorder: Root → Left → Right.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:266
Question: Inorder Traversal of Binary Tree

� Inorder Traversal of a Binary Tree in C++

Inorder traversal follows the order: Left → Root → Right

cpp

#include <iostream>

using namespace std;

// Definition of a binary tree nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Inorder traversal functionvoid inorder(Node* root) {

if (root == nullptr) return;

inorder(root->left);

cout << root->data << " ";

inorder(root->right);

int main() {

// Creating a binary tree

Node* root = new Node(1);

root->left = new Node(2);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Inorder Traversal: ";

inorder(root);

return 0;

� Code Explanation (in 4 lines):

1. A Node class defines the structure of each tree node.


2. The inorder() function recursively visits the left child, prints the root, then
visits the right child.
3. In main(), we build a binary tree with 5 nodes manually.
4. The output of inorder(root) follows the left → root → right traversal
pattern.

PROBLEM:267
Question: Post-order Traversal of Binary Tree

� Post-order Traversal of a Binary Tree in C++

Post-order traversal follows the order: Left → Right → Root

cpp

#include <iostream>

using namespace std;

// Definition of a binary tree nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


data = val;

left = right = nullptr;

};

// Post-order traversal functionvoid postorder(Node* root) {

if (root == nullptr) return;

postorder(root->left);

postorder(root->right);

cout << root->data << " ";

int main() {

// Creating a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Post-order Traversal: ";

postorder(root);

return 0;

� Code Explanation (in 4 lines):

1. A Node class is used to define the structure of each binary tree node.
2. The postorder() function first visits left and right children, then prints the root
node.
3. In main(), we manually create a binary tree with a few nodes.
4. postorder(root) outputs nodes in post-order: Left → Right → Root.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:268
Question: Level order Traversal / Level order traversal in spiral form

� Level Order Traversal and Spiral (Zigzag) Traversal in C++

Level Order Traversal means visiting nodes level by level, while Spiral (Zigzag)
Traversal alternates the direction of traversal at each level.

✅ Level Order Traversal using Queue:

cpp

#include <iostream>

#include <queue>

using namespace std;

class Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Level Order Traversalvoid levelOrder(Node* root) {

if (root == nullptr) return;

queue<Node*> q;

q.push(root);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (!q.empty()) {

Node* curr = q.front();

q.pop();

cout << curr->data << " ";

if (curr->left) q.push(curr->left);

if (curr->right) q.push(curr->right);

� Spiral (Zigzag) Level Order Traversal using 2 Stacks:

cpp

#include <stack>

// Spiral Order Traversalvoid spiralOrder(Node* root) {

if (root == nullptr) return;

stack<Node*> s1; // Left to Right

stack<Node*> s2; // Right to Left

s1.push(root);

while (!s1.empty() || !s2.empty()) {

// Print left to right

while (!s1.empty()) {

Node* temp = s1.top(); s1.pop();

cout << temp->data << " ";

if (temp->left) s2.push(temp->left);

if (temp->right) s2.push(temp->right);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Print right to left

while (!s2.empty()) {

Node* temp = s2.top(); s2.pop();

cout << temp->data << " ";

if (temp->right) s1.push(temp->right);

if (temp->left) s1.push(temp->left);

� Code Explanation (in 4 lines):

1. Level Order uses a queue to print nodes from top to bottom and left to right.
2. Spiral Order uses two stacks to alternate directions at each level: L→R and R→L.
3. The main() function builds a binary tree and calls both traversal functions.
4. These methods are useful in problems where you need to process tree levels in
order or in zigzag pattern.

PROBLEM:269
Question: Iterative Preorder Traversal of Binary Tree

� Iterative Preorder Traversal of a Binary Tree in C++

Instead of using recursion, we can use a stack to simulate Preorder traversal (Root
→ Left → Right).

✅ C++ Code:

cpp

#include <iostream>

#include <stack>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Iterative Preorder Traversalvoid iterativePreorder(Node* root) {

if (root == nullptr) return;

stack<Node*> st;

st.push(root);

while (!st.empty()) {

Node* curr = st.top();

st.pop();

cout << curr->data << " ";

// Push right child first so left is processed first

if (curr->right) st.push(curr->right);

if (curr->left) st.push(curr->left);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

// Create a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Iterative Preorder Traversal: ";

iterativePreorder(root);

return 0;

� Code Explanation (in 4 lines):

1. A Node class is defined with left and right pointers for binary tree structure.
2. We use a stack to mimic recursive call behavior and process nodes manually.
3. Push right child first so that left child gets processed first (stack = LIFO).
4. The traversal outputs nodes in Preorder: Root → Left → Right, without recursion.

PROBLEM:270
Question: Iterative Inorder Traversal of Binary Tree

� Iterative Inorder Traversal of a Binary Tree in C++

In Inorder Traversal, the order is: Left → Root → Right.


We can do this iteratively using a stack to simulate the recursion.

✅ C++ Code:

cpp

#include <iostream>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <stack>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Iterative Inorder Traversalvoid iterativeInorder(Node* root) {

stack<Node*> st;

Node* curr = root;

while (curr != nullptr || !st.empty()) {

// Reach the leftmost node

while (curr != nullptr) {

st.push(curr);

curr = curr->left;

// Visit the node

curr = st.top();

st.pop();

cout << curr->data << " ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Go to the right subtree

curr = curr->right;

int main() {

// Create a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Iterative Inorder Traversal: ";

iterativeInorder(root);

return 0;

� Code Explanation (in 4 lines):

1. We use a stack to keep track of nodes while exploring the left subtree.
2. Once the leftmost node is reached, we visit the node and move to its right subtree.
3. This mimics recursive behavior but avoids using function calls.
4. The traversal prints nodes in Inorder: Left → Root → Right.

PROBLEM:271
Question: Post-order Traversal of Binary Tree using 2 stack

� Iterative Post-order Traversal of a Binary Tree Using 2 Stacks (C++)

Post-order traversal follows the order: Left → Right → Root.


To perform this iteratively, we can use two stacks to simulate the traversal.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ C++ Code:

cpp

#include <iostream>

#include <stack>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Post-order traversal using 2 stacksvoid postorderIterative(Node* root) {

if (root == nullptr) return;

stack<Node*> s1, s2;

s1.push(root);

// First stack is used for processing nodes

while (!s1.empty()) {

Node* curr = s1.top();

s1.pop();

s2.push(curr); // Save root in second stack

// Push left and right children

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (curr->left) s1.push(curr->left);

if (curr->right) s1.push(curr->right);

// Second stack gives post-order output

while (!s2.empty()) {

cout << s2.top()->data << " ";

s2.pop();

int main() {

// Create a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Post-order Traversal (Iterative using 2 stacks): ";

postorderIterative(root);

return 0;

� Code Explanation (in 4 lines):

1. The first stack is used to simulate root → right → left traversal (reverse post-
order).
2. The second stack stores nodes in reverse, resulting in Left → Right → Root order.
3. After all nodes are pushed into the second stack, we pop and print them.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4. This efficiently performs post-order traversal without recursion.

PROBLEM:272
Question: Post-order Traversal of Binary Tree using 1 stack

� Iterative Post-order Traversal of a Binary Tree Using 1 Stack (C++)

Post-order traversal order is: Left → Right → Root.


It’s trickier with one stack, but doable by tracking the last visited node.

✅ C++ Code:

cpp

#include <iostream>

#include <stack>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Iterative Post-order Traversal using 1 stackvoid postorderIterative(Node* root) {

if (root == nullptr) return;

stack<Node*> st;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* curr = root;

Node* lastVisited = nullptr;

while (!st.empty() || curr != nullptr) {

if (curr != nullptr) {

st.push(curr);

curr = curr->left; // Move to left subtree

} else {

Node* peekNode = st.top();

// If right child exists and is not visited

if (peekNode->right != nullptr && lastVisited != peekNode->right) {

curr = peekNode->right;

} else {

cout << peekNode->data << " ";

lastVisited = peekNode;

st.pop();

int main() {

// Create a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Post-order Traversal (Iterative using 1 stack): ";

postorderIterative(root);

return 0;

� Code Explanation (in 4 lines):

1. We use a single stack to simulate traversal and a pointer to track the last visited
node.
2. We go as left as possible, then check if the right child has been visited.
3. If not, move to the right; else process the node and mark it as visited.
4. This gives the correct Post-order traversal without recursion or extra stacks.

PROBLEM:273
Question : Preorder, Inorder, and Postorder Traversal in one Traversal

� Preorder, Inorder, and Postorder Traversals in One Traversal (C++


Solution)

You can compute all three tree traversals — Preorder, Inorder, and Postorder —
in a single iterative traversal using a stack and a tracking mechanism.

✅ C++ Code (All Three in One Pass):

cpp

#include <iostream>

#include <stack>

#include <vector>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node(int val) {

data = val;

left = right = nullptr;

};

// Helper structure to pair node with its statestruct Pair {

Node* node;

int state;

};

void allTraversals(Node* root, vector<int>& pre, vector<int>& in, vector<int>& post) {

if (root == nullptr) return;

stack<Pair> st;

st.push({root, 1});

while (!st.empty()) {

Pair& p = st.top();

if (p.state == 1) {

// Preorder

pre.push_back(p.node->data);

p.state++;

if (p.node->left)

st.push({p.node->left, 1});

else if (p.state == 2) {

// Inorder

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


in.push_back(p.node->data);

p.state++;

if (p.node->right)

st.push({p.node->right, 1});

else {

// Postorder

post.push_back(p.node->data);

st.pop();

int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

vector<int> preorder, inorder, postorder;

allTraversals(root, preorder, inorder, postorder);

cout << "Preorder: ";

for (int val : preorder) cout << val << " ";

cout << "\nInorder: ";

for (int val : inorder) cout << val << " ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "\nPostorder: ";

for (int val : postorder) cout << val << " ";

return 0;

� Code Explanation (in 4 lines):

1. We use a Pair (node + state) to track the current phase of traversal for each node.
2. When state == 1, it's Preorder, then move to the left child.
3. When state == 2, it's Inorder, then move to the right child.
4. When state == 3, it's Postorder, then we finish and pop the node from the stack.

PROBLEM:274
Question : Height of a Binary Tree

� Height of a Binary Tree in C++

The height of a binary tree is the number of edges on the longest path from the
root to a leaf node.

✅ C++ Code to Calculate Height (Recursive):

cpp

#include <iostream>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


left = right = nullptr;

};

// Function to calculate height of the treeint height(Node* root) {

if (root == nullptr)

return 0;

int leftHeight = height(root->left);

int rightHeight = height(root->right);

return 1 + max(leftHeight, rightHeight);

int main() {

// Create a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Height of Binary Tree: " << height(root);

return 0;

� Code Explanation (in 4 lines):

1. A Node class is used to define binary tree structure.


2. The height() function recursively calculates the height of left and right subtrees.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3. The maximum of the two is taken and +1 is added for the current node.
4. This function returns the total height (depth) of the tree from root to the deepest
leaf.

PROBLEM:275
Question : Check if the Binary tree is height-balanced or not

⚖️ Check if a Binary Tree is Height-Balanced (C++)

A height-balanced binary tree is one where the difference between heights of


left and right subtrees is at most 1 for every node.

✅ C++ Code to Check Balance (Efficient O(n)):

cpp

#include <iostream>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Helper function to check balance and compute heightint checkHeight(Node* root) {

if (root == nullptr)

return 0;

int left = checkHeight(root->left);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (left == -1) return -1; // Left subtree not balanced

int right = checkHeight(root->right);

if (right == -1) return -1; // Right subtree not balanced

if (abs(left - right) > 1)

return -1; // Current node unbalanced

return 1 + max(left, right); // Return height

// Main function to check if tree is balancedbool isBalanced(Node* root) {

return checkHeight(root) != -1;

int main() {

// Create a binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->left->left = new Node(3); // Unbalanced example

if (isBalanced(root))

cout << "The Binary Tree is Balanced.\n";

else

cout << "The Binary Tree is Not Balanced.\n";

return 0;

� Code Explanation (in 4 lines):

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. We use a helper checkHeight() that returns -1 if a subtree is unbalanced.
2. It recursively calculates the height and checks the difference for each node.
3. If any node is unbalanced, the result is propagated up by returning -1.
4. isBalanced() returns true only if the full tree is height-balanced.

PROBLEM:276
Question : Diameter of Binary Tree

� Diameter of a Binary Tree in C++

The diameter (or width) of a binary tree is the length of the longest path between
any two nodes, which may or may not pass through the root. It is measured as
the number of nodes on the path (or edges, depending on definition — here we'll
count edges).

✅ C++ Code to Calculate Diameter (Efficient O(n)):

cpp

#include <iostream>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Helper function to calculate height and update diameterint height(Node* root, int& diameter)
{

if (root == nullptr)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

int leftHeight = height(root->left, diameter);

int rightHeight = height(root->right, diameter);

// Update diameter at this node

diameter = max(diameter, leftHeight + rightHeight);

return 1 + max(leftHeight, rightHeight);

// Main function to get diameterint getDiameter(Node* root) {

int diameter = 0;

height(root, diameter);

return diameter;

int main() {

// Create binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Diameter of the Binary Tree: " << getDiameter(root);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation (in 4 lines):

1. We use a helper function that returns height while also updating the diameter
reference.
2. The diameter at each node is calculated as left height + right height.
3. The maximum of these values is stored as the final diameter.
4. This ensures an efficient O(n) solution in a single traversal.

PROBLEM:277
Question : Maximum path sum

� Maximum Path Sum in a Binary Tree (C++ Code)

The maximum path sum is the highest sum of values from any path in the tree.
A path can start and end at any node, and must go downward (no cycles).

✅ C++ Code (Handles All Cases):

cpp

#include <iostream>

#include <climits>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Helper function to compute max path sumint maxPathDown(Node* root, int& maxSum) {

if (root == nullptr)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

int left = max(0, maxPathDown(root->left, maxSum)); // ignore negatives

int right = max(0, maxPathDown(root->right, maxSum));

// Update maxSum considering current node as root of the path

maxSum = max(maxSum, left + right + root->data);

// Return max path sum going downward from current node

return root->data + max(left, right);

// Main function to get max path sumint maxPathSum(Node* root) {

int maxSum = INT_MIN;

maxPathDown(root, maxSum);

return maxSum;

int main() {

// Create binary tree

Node* root = new Node(-10);

root->left = new Node(9);

root->right = new Node(20);

root->right->left = new Node(15);

root->right->right = new Node(7);

cout << "Maximum Path Sum: " << maxPathSum(root);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation (in 4 lines):

1. We recursively calculate the maximum gain from left and right subtrees (ignoring
negatives).
2. At each node, we update the global maxSum considering the full path through it.
3. Only one side (left or right) can be returned to the parent (no forks going up).
4. This ensures we get the maximum path sum between any two nodes.

PROBLEM:278
Question : Check if two trees are identical or not

�✅ Check if Two Binary Trees Are Identical (C++ Code)

Two binary trees are identical if they have:

The same structure, and

The same node values at every corresponding position.

✅ C++ Code to Compare Two Trees:

cpp

#include <iostream>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to check if two trees are identicalbool isIdentical(Node* root1, Node* root2) {

if (root1 == nullptr && root2 == nullptr)

return true;

if (root1 == nullptr || root2 == nullptr)

return false;

return (root1->data == root2->data) &&

isIdentical(root1->left, root2->left) &&

isIdentical(root1->right, root2->right);

int main() {

// Tree 1

Node* root1 = new Node(1);

root1->left = new Node(2);

root1->right = new Node(3);

// Tree 2

Node* root2 = new Node(1);

root2->left = new Node(2);

root2->right = new Node(3);

if (isIdentical(root1, root2))

cout << "The trees are identical.\n";

else

cout << "The trees are NOT identical.\n";

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Code Explanation (in 4 lines):

1. If both trees are empty (nullptr), they are identical.


2. If only one is nullptr, they differ.
3. Check if current node values match, and recursively compare left and right
subtrees.
4. Returns true only if structure and data match exactly.

PROBLEM:279
Question : Zig Zag Traversal of Binary Tree

� Zig-Zag (Spiral) Traversal of a Binary Tree in C++

Zig-Zag Traversal is a level order traversal where:

Odd levels are printed left to right,

Even levels are printed right to left.

✅ C++ Code for Zig-Zag Traversal:

cpp

#include <iostream>#include <stack>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Zig-Zag Traversal using two stacksvoid zigzagTraversal(Node* root) {

if (root == nullptr) return;

stack<Node*> currentLevel;

stack<Node*> nextLevel;

bool leftToRight = true;

currentLevel.push(root);

while (!currentLevel.empty()) {

Node* temp = currentLevel.top();

currentLevel.pop();

if (temp) {

cout << temp->data << " ";

// Push children in opposite order depending on level

if (leftToRight) {

if (temp->left) nextLevel.push(temp->left);

if (temp->right) nextLevel.push(temp->right);

} else {

if (temp->right) nextLevel.push(temp->right);

if (temp->left) nextLevel.push(temp->left);

// If current level is done, switch

if (currentLevel.empty()) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


leftToRight = !leftToRight;

swap(currentLevel, nextLevel);

int main() {

// Create binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->right->left = new Node(6);

root->right->right = new Node(7);

cout << "Zig-Zag Traversal: ";

zigzagTraversal(root);

return 0;

� Code Explanation (in 4 lines):

1. Use two stacks to alternate between levels.


2. Push children in left-right or right-left order depending on the level.
3. After finishing one level, swap the stacks and toggle direction.
4. This prints the tree in Zig-Zag / Spiral order efficiently.

PROBLEM:280
Question : Boundary Traversal of Binary Tree

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


�� Boundary Traversal of a Binary Tree (C++ Code)

Boundary Traversal of a binary tree involves printing nodes in this specific order:

Left Boundary (excluding leaves)

All Leaf Nodes (left to right)

Right Boundary (excluding leaves, in reverse)

✅ C++ Code for Boundary Traversal:

cpp

#include <iostream>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Check if a node is a leafbool isLeaf(Node* node) {

return (node->left == nullptr && node->right == nullptr);

// Print left boundary (excluding leaves)void printLeftBoundary(Node* node) {

while (node) {

if (!isLeaf(node)) cout << node->data << " ";

if (node->left) node = node->left;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else node = node->right;

// Print all leaf nodes (left to right)void printLeaves(Node* node) {

if (node == nullptr) return;

printLeaves(node->left);

if (isLeaf(node)) cout << node->data << " ";

printLeaves(node->right);

// Print right boundary (excluding leaves, in reverse)void printRightBoundary(Node* node) {

if (node == nullptr) return;

if (!isLeaf(node)) {

if (node->right) printRightBoundary(node->right);

else printRightBoundary(node->left);

cout << node->data << " "; // Print after recursion for reverse order

// Main function to perform boundary traversalvoid boundaryTraversal(Node* root) {

if (root == nullptr) return;

// Root node (only if not leaf)

if (!isLeaf(root)) cout << root->data << " ";

printLeftBoundary(root->left);

printLeaves(root);

printRightBoundary(root->right);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->right->left = new Node(6);

root->right->right = new Node(7);

cout << "Boundary Traversal: ";

boundaryTraversal(root);

return 0;

� Code Explanation :

1. Print the root (if it’s not a leaf).


2. Traverse and print the left boundary, skipping leaf nodes.
3. Print all leaf nodes using in-order traversal.

PROBLEM:281
Question : Vertical Order Traversal of Binary Tree

�️ Vertical Order Traversal of a Binary Tree (C++ Code)

Vertical Order Traversal groups the binary tree nodes by their horizontal distance
from the root:

Nodes on the same vertical line are printed together, from top to bottom.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ C++ Code for Vertical Order Traversal:

cpp

#include <iostream>

#include <map>

#include <queue>

#include <vector>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Function to perform vertical order traversalvoid verticalOrderTraversal(Node* root) {

if (!root) return;

// Map to store: horizontal distance -> list of nodes at that distance

map<int, vector<int>> nodes;

// Queue to store pairs of node and its horizontal distance

queue<pair<Node*, int>> q;

q.push({root, 0});

while (!q.empty()) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


auto front = q.front();

q.pop();

Node* curr = front.first;

int hd = front.second;

nodes[hd].push_back(curr->data);

if (curr->left) q.push({curr->left, hd - 1});

if (curr->right) q.push({curr->right, hd + 1});

// Print nodes in vertical order

for (auto& pair : nodes) {

for (int val : pair.second)

cout << val << " ";

int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->right->left = new Node(6);

root->right->right = new Node(7);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Vertical Order Traversal: ";

verticalOrderTraversal(root);

return 0;

� Code Explanation (in 4 lines):

1. We use a queue to do level order traversal while tracking horizontal distance


(hd).
2. A map stores lists of nodes grouped by their hd (vertical level).
3. Nodes are added left as hd-1 and right as hd+1.

PROBLEM:282
Question : Top View of Binary Tree

� Top View of a Binary Tree (C++ Code)

The top view of a binary tree is the set of nodes visible when the tree is viewed from
the top.

For each vertical line, only the first node (topmost) encountered is included.

✅ C++ Code for Top View Traversal:

cpp

#include <iostream>

#include <map>

#include <queue>

using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node(int val) {

data = val;

left = right = nullptr;

};

// Function to print top viewvoid topView(Node* root) {

if (root == nullptr) return;

// Map to store: horizontal distance -> first node at that distance

map<int, int> topNode;

// Queue to hold nodes with their horizontal distance

queue<pair<Node*, int>> q;

q.push({root, 0});

while (!q.empty()) {

auto [node, hd] = q.front();

q.pop();

// Insert the node if this horizontal distance is not yet filled

if (topNode.find(hd) == topNode.end()) {

topNode[hd] = node->data;

if (node->left) q.push({node->left, hd - 1});

if (node->right) q.push({node->right, hd + 1});

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Print the top view (sorted by horizontal distance)

for (auto& it : topNode)

cout << it.second << " ";

int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->right = new Node(4);

root->left->right->right = new Node(5);

root->left->right->right->right = new Node(6);

cout << "Top View of Binary Tree: ";

topView(root);

return 0;

� Code Explanation (in 4 lines):

1. Perform a level order traversal while tracking horizontal distance (hd).


2. Use a map to store the first node seen at each horizontal level.
3. Insert into the map only if hd not yet present (topmost node).
4. Print map values in order of increasing hd to get the top view.

PROBLEM:283
Question : Bottom View of Binary Tree

� Bottom View of a Binary Tree (C++ Code)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The bottom view of a binary tree includes the last (lowest) node visible at each
vertical level when the tree is viewed from the bottom.

✅ C++ Code for Bottom View Traversal:

cpp

#include <iostream>#include <map>#include <queue>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Function to print bottom viewvoid bottomView(Node* root) {

if (root == nullptr) return;

// Map to store horizontal distance -> latest node at that distance

map<int, int> bottomNode;

// Queue to hold nodes with their horizontal distance

queue<pair<Node*, int>> q;

q.push({root, 0});

while (!q.empty()) {

auto [node, hd] = q.front();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


q.pop();

// Update the node at this horizontal distance (overwrite)

bottomNode[hd] = node->data;

if (node->left) q.push({node->left, hd - 1});

if (node->right) q.push({node->right, hd + 1});

// Print the bottom view (sorted by horizontal distance)

for (auto& it : bottomNode)

cout << it.second << " ";

int main() {

// Construct binary tree

Node* root = new Node(20);

root->left = new Node(8);

root->right = new Node(22);

root->left->left = new Node(5);

root->left->right = new Node(3);

root->right->left = new Node(4);

root->right->right = new Node(25);

root->left->right->left = new Node(10);

root->left->right->right = new Node(14);

cout << "Bottom View of Binary Tree: ";

bottomView(root);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Code Explanation (in 4 lines):

1. Perform level order traversal with horizontal distance (hd) tracking.


2. For each node, overwrite the current value in the map (to get bottom-most).
3. map<int, int> ensures vertical levels are sorted.
4. Final map values give the bottom view from leftmost to rightmost vertical line.

PROBLEM:284
Question : Right/Left View of Binary Tree

�️ Left and Right View of a Binary Tree in C++

Left View: Nodes visible when tree is viewed from the left side — first node at
each level.

Right View: Nodes visible when tree is viewed from the right side — last node at
each level.

✅ C++ Code for Left and Right View:

cpp

#include <iostream>#include <queue>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

// Function for Left Viewvoid leftView(Node* root) {

if (!root) return;

queue<Node*> q;

q.push(root);

while (!q.empty()) {

int size = q.size(); // nodes at current level

for (int i = 0; i < size; ++i) {

Node* node = q.front();

q.pop();

// First node at current level

if (i == 0)

cout << node->data << " ";

if (node->left) q.push(node->left);

if (node->right) q.push(node->right);

// Function for Right Viewvoid rightView(Node* root) {

if (!root) return;

queue<Node*> q;

q.push(root);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (!q.empty()) {

int size = q.size(); // nodes at current level

for (int i = 0; i < size; ++i) {

Node* node = q.front();

q.pop();

// Last node at current level

if (i == size - 1)

cout << node->data << " ";

if (node->left) q.push(node->left);

if (node->right) q.push(node->right);

int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->right->right = new Node(6);

cout << "Left View: ";

leftView(root);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "\nRight View: ";

rightView(root);

return 0;

� Code Explanation (in 4 lines):

1. Use level order traversal with a queue.


2. For left view, print the first node at each level.
3. For right view, print the last node at each level.
4. Queue ensures all levels are visited in order from top to bottom.

PROBLEM:285
Question : Symmetric Binary Tree

� Symmetric Binary Tree (C++ Code)

A binary tree is symmetric if it is a mirror image of itself — the left and right
subtrees must be mirror reflections.

✅ C++ Code to Check Symmetry:

cpp

#include <iostream>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

};

// Helper function to check mirror symmetrybool isMirror(Node* t1, Node* t2) {

if (t1 == nullptr && t2 == nullptr) return true;

if (t1 == nullptr || t2 == nullptr) return false;

return (t1->data == t2->data) &&

isMirror(t1->left, t2->right) &&

isMirror(t1->right, t2->left);

// Main function to check if tree is symmetricbool isSymmetric(Node* root) {

return isMirror(root, root);

int main() {

// Symmetric tree example

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(2);

root->left->left = new Node(3);

root->left->right = new Node(4);

root->right->left = new Node(4);

root->right->right = new Node(3);

cout << (isSymmetric(root) ? "Tree is symmetric\n" : "Tree is not symmetric\n");

return 0;

� Code Explanation (in 4 lines):

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. A tree is symmetric if its left and right subtrees are mirror images.
2. isMirror() compares two subtrees for symmetry recursively.
3. It checks data match, and cross-subtree symmetry (left with right and
right with left).
4. The main function compares the tree with itself to validate symmetry.

PROBLEM:286
Question : Root to Node Path in Binary Tree

�➡️� Root to Node Path in a Binary Tree (C++ Code)

This problem involves finding the path from the root to a given node.
We’ll use DFS (Depth First Search) with backtracking to track the path.

✅ C++ Code to Find Root-to-Node Path:

cpp

#include <iostream>#include <vector>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Helper function to find pathbool getPath(Node* root, vector<int>& path, int target) {

if (!root) return false;

path.push_back(root->data);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// If current node is the target

if (root->data == target) return true;

// Recursively check left and right

if (getPath(root->left, path, target) || getPath(root->right, path, target))

return true;

// Backtrack if not found in this path

path.pop_back();

return false;

int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

int target = 5;

vector<int> path;

if (getPath(root, path, target)) {

cout << "Path from root to node " << target << ": ";

for (int val : path)

cout << val << " ";

} else {

cout << "Node not found in tree.";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return 0;

� Code Explanation (in 4 lines):

1. Use DFS to traverse the tree while storing nodes in a path vector.
2. If the target node is found, return true and keep the path.
3. If not found in a subtree, backtrack (remove the last node).
4. Print the path if the node exists; otherwise, show not found.

PROBLEM:287
Question : LCA in Binary Tree

� Lowest Common Ancestor (LCA) in a Binary Tree — C++ Code

The Lowest Common Ancestor (LCA) of two nodes n1 and n2 in a binary tree is the
deepest node that is an ancestor of both.

✅ C++ Code to Find LCA:

cpp

#include <iostream>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

// Function to find LCA of two nodesNode* findLCA(Node* root, int n1, int n2) {

if (!root) return nullptr;

// If either n1 or n2 matches root, this node could be LCA

if (root->data == n1 || root->data == n2) return root;

// Recur for left and right subtree

Node* leftLCA = findLCA(root->left, n1, n2);

Node* rightLCA = findLCA(root->right, n1, n2);

// If both sides return non-null, root is the LCA

if (leftLCA && rightLCA) return root;

// Else return the non-null child

return (leftLCA != nullptr) ? leftLCA : rightLCA;

int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->right->left = new Node(6);

root->right->right = new Node(7);

int n1 = 4, n2 = 5;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* lca = findLCA(root, n1, n2);

if (lca)

cout << "LCA of " << n1 << " and " << n2 << " is: " << lca->data << endl;

else

cout << "LCA not found.\n";

return 0;

� Code Explanation (in 4 lines):

1. Recursively search for n1 and n2 in left and right subtrees.


2. If both sides return non-null, current node is the LCA.
3. If only one side returns non-null, bubble it up as potential LCA.
4. If root matches either n1 or n2, it could be the LCA itself.

PROBLEM:288
Question : Maximum width of a Binary Tree

� Maximum Width of a Binary Tree — C++ Code

The maximum width of a binary tree is the maximum number of nodes present at
any level (including null nodes in between in a complete level view).

✅ C++ Code to Find Maximum Width:

cpp

#include <iostream>#include <queue>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Function to calculate maximum widthint getMaxWidth(Node* root) {

if (!root) return 0;

int maxWidth = 0;

// Queue stores pair of node and its index (for complete tree representation)

queue<pair<Node*, int>> q;

q.push({root, 0});

while (!q.empty()) {

int size = q.size();

int minIndex = q.front().second; // to normalize index

int first, last;

for (int i = 0; i < size; ++i) {

int curIndex = q.front().second - minIndex; // normalized index

Node* node = q.front().first;

q.pop();

if (i == 0) first = curIndex;

if (i == size - 1) last = curIndex;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (node->left) q.push({node->left, 2 * curIndex + 1});

if (node->right) q.push({node->right, 2 * curIndex + 2});

maxWidth = max(maxWidth, last - first + 1);

return maxWidth;

int main() {

// Construct binary tree

Node* root = new Node(1);

root->left = new Node(3);

root->right = new Node(2);

root->left->left = new Node(5);

root->left->right = new Node(3);

root->right->right = new Node(9);

cout << "Maximum Width of Binary Tree: " << getMaxWidth(root) << endl;

return 0;

� Code Explanation (in 4 lines):

1. Use a queue for level-order traversal, tracking each node’s position index.
2. Normalize indices at each level to avoid overflow.
3. Width = last_index - first_index + 1 at each level.
4. Return the maximum width encountered across all levels.

PROBLEM:289

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Check for Children Sum Property

�➕� = ️ Children Sum Property in a Binary Tree (C++ Code)

A binary tree satisfies the children sum property if for every non-leaf node,
the node’s value is equal to the sum of its left and right child’s values.

✅ C++ Code to Check Children Sum Property:

cpp

#include <iostream>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Function to check the Children Sum Propertybool checkChildrenSum(Node* root) {

// Base case: empty tree or leaf node

if (!root || (!root->left && !root->right))

return true;

int leftData = (root->left) ? root->left->data : 0;

int rightData = (root->right) ? root->right->data : 0;

bool currentNodeValid = (root->data == leftData + rightData);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Recursively check left and right subtree

return currentNodeValid && checkChildrenSum(root->left) && checkChildrenSum(root-


>right);

int main() {

// Construct a binary tree

Node* root = new Node(10);

root->left = new Node(8);

root->right = new Node(2);

root->left->left = new Node(3);

root->left->right = new Node(5);

root->right->right = new Node(2);

if (checkChildrenSum(root))

cout << "Tree satisfies the Children Sum Property\n";

else

cout << "Tree does NOT satisfy the Children Sum Property\n";

return 0;

� Code Explanation (in 4 lines):

1. For each node, compare its value with the sum of its left and right child.
2. If any node violates the property, return false.
3. Leaf nodes and nulls are considered valid by default.
4. Recursively check the entire tree for children sum compliance.

PROBLEM:290
Question : Print all the Nodes at a distance of K in a Binary Tree

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Print All Nodes at Distance K in a Binary Tree — C++ Code

There are two variations:

Nodes at distance K from the root.

Nodes at distance K from a given target node.

Here, we'll do both versions step by step.

✅ 1. From Root (Simple Recursive DFS)


cpp

#include <iostream>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Print all nodes at distance K from rootvoid printKDistance(Node* root, int k) {

if (!root) return;

if (k == 0) {

cout << root->data << " ";

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


printKDistance(root->left, k - 1);

printKDistance(root->right, k - 1);

int main() {

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->right->left = new Node(6);

root->right->right = new Node(7);

int k = 2;

cout << "Nodes at distance " << k << " from root: ";

printKDistance(root, k);

return 0;

� Explanation (Root Version - 4 Lines):


1. Use recursion to go down the tree, reducing k at each level.
2. When k == 0, print the node.
3. Ignore null nodes.
4. This prints all nodes exactly k edges away from root.

✅ 2. From a Target Node (General Case)


To find nodes at distance K from a target node, we:

Find the path from target to ancestors

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Traverse subtrees and other branches using distance left

PROBLEM:291
Question : Minimum time taken to BURN the Binary Tree from a Node

�� Minimum Time to Burn a Binary Tree from a Given Node (C++ Code)

You're given a binary tree and a target node from which a fire starts.
Each second, fire spreads to adjacent nodes (parent, left, right).
You need to find the minimum time to burn the entire tree.

� Key Idea:

 Treat the tree like a graph: each node is connected to its children and its
parent.
 Use BFS traversal from the target node to simulate fire spread.
 Count time units as levels in BFS.

✅ Step-by-Step C++ Code:

cpp

#include <iostream>#include <unordered_map>#include <unordered_set>#include


<queue>using namespace std;

// Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

// Step 1: Map each node to its parent and find the target nodevoid mapParents(Node* root,
unordered_map<Node*, Node*>& parentMap, Node*& targetNode, int target) {

queue<Node*> q;

q.push(root);

while (!q.empty()) {

Node* node = q.front(); q.pop();

if (node->data == target) targetNode = node;

if (node->left) {

parentMap[node->left] = node;

q.push(node->left);

if (node->right) {

parentMap[node->right] = node;

q.push(node->right);

// Step 2: BFS to simulate fire spreading and calculate timeint burnTree(Node* targetNode,
unordered_map<Node*, Node*>& parentMap) {

unordered_set<Node*> visited;

queue<Node*> q;

q.push(targetNode);

visited.insert(targetNode);

int time = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (!q.empty()) {

int size = q.size();

bool burnedNewNode = false;

for (int i = 0; i < size; ++i) {

Node* node = q.front(); q.pop();

for (Node* neighbor : {node->left, node->right, parentMap[node]}) {

if (neighbor && visited.find(neighbor) == visited.end()) {

burnedNewNode = true;

visited.insert(neighbor);

q.push(neighbor);

if (burnedNewNode) time++;

return time;

int minTimeToBurnTree(Node* root, int target) {

unordered_map<Node*, Node*> parentMap;

Node* targetNode = nullptr;

mapParents(root, parentMap, targetNode, target);

return burnTree(targetNode, parentMap);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Main functionint main() {

// Example Tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->left->right->left = new Node(6);

root->right->right = new Node(7);

int target = 5;

cout << "Minimum time to burn the tree from node " << target << ": " <<
minTimeToBurnTree(root, target) << " seconds\n";

return 0;

� Code Explanation in 4 Lines:

1. Map each node to its parent while locating the target node.
2. Start BFS from the target, simulating fire spreading to neighbors (left, right,
parent).
3. Use a visited set to avoid revisiting burned nodes.
4. Each BFS level = 1 second of burning; return the total time.

PROBLEM:292
Question : Count total Nodes in a COMPLETE Binary Tree

�� Count Total Nodes in a Complete Binary Tree — C++ Code

A Complete Binary Tree has all levels completely filled,


except possibly the last, which is filled from left to right.

We can optimize node counting to O(log² N) instead of O(N) using height checks.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ Optimized C++ Code:

cpp

#include <iostream>#include <cmath>using namespace std;

// Binary Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Function to calculate height of leftmost or rightmost pathint getLeftHeight(Node* node) {

int height = 0;

while (node) {

height++;

node = node->left;

return height;

int getRightHeight(Node* node) {

int height = 0;

while (node) {

height++;

node = node->right;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return height;

// Main Function to count nodes in a Complete Binary Treeint countNodes(Node* root) {

if (!root) return 0;

int lh = getLeftHeight(root);

int rh = getRightHeight(root);

// If tree is perfect, use formula 2^h - 1

if (lh == rh) return (1 << lh) - 1;

// Otherwise, recurse both subtrees

return 1 + countNodes(root->left) + countNodes(root->right);

int main() {

// Constructing a Complete Binary Tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

root->right->left = new Node(6);

cout << "Total Nodes in Complete Binary Tree: " << countNodes(root) << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation in 4 Lines:

1. For each node, calculate left and right heights.


2. If they’re equal, it’s a perfect subtree, so use 2^h - 1 formula.
3. Otherwise, recursively count left and right nodes.
4. This gives a log²(N) time solution for complete binary trees.

PROBLEM:293
Question : Requirements needed to construct a Unique Binary Tree | Theory

�� Requirements to Construct a Unique Binary Tree — Theory

Constructing a unique binary tree means there's only one possible tree for the
given input. To achieve this, the type and combination of traversal orders provided
must contain enough information.

✅ Key Theoretical Requirements:

✅ 1. Inorder + Preorder Traversal

✅ Unique tree possible.

Inorder gives the left-right structure,


Preorder gives the root-first order.

Use case: You know the structure and order of root placement.

✅ 2. Inorder + Postorder Traversal

✅ Also results in a unique tree.

Postorder gives root-last order,


Inorder still gives structure.

Used when processing bottom-up.

❌ 3. Preorder + Postorder (No Inorder)

❌ Does NOT guarantee a unique tree in general.

Exception: If the tree is full (every node has 0 or 2 children),


then a unique tree can be constructed.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


❌ 4. Only Inorder / Preorder / Postorder

❌ Not sufficient alone to construct a unique binary tree.

Multiple different trees can generate the same single traversal.

� Summary Table:

Traversals Given Unique Tree? Notes

Inorder + Preorder ✅ Yes Most commonly used combo

Inorder + Postorder ✅ Yes Also works well

Preorder + Postorder ❌ No Ambiguous (unless full binary)

Only one traversal ❌ No Not sufficient info

PROBLEM:294
Question : Construct Binary Tree from inorder and preorder

�� Construct Binary Tree from Inorder and Preorder Traversals (C++ Code)

Given two arrays:

preorder[] → Root → Left → Right

inorder[] → Left → Root → Right

Your task is to construct the unique binary tree from these traversals.

✅ C++ Code:

cpp

#include <iostream>#include <unordered_map>using namespace std;

// Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node(int val) {

data = val;

left = right = nullptr;

};

// Build tree functionNode* buildTree(int preorder[], int inorder[], int inStart, int inEnd,

int& preIndex, unordered_map<int, int>& inMap) {

if (inStart > inEnd) return nullptr;

int rootVal = preorder[preIndex++];

Node* root = new Node(rootVal);

int inIndex = inMap[rootVal];

// Build left and right subtrees

root->left = buildTree(preorder, inorder, inStart, inIndex - 1, preIndex, inMap);

root->right = buildTree(preorder, inorder, inIndex + 1, inEnd, preIndex, inMap);

return root;

// Helper function to build using maps and start main logicNode* buildTreeFromPreIn(int
preorder[], int inorder[], int n) {

unordered_map<int, int> inMap;

for (int i = 0; i < n; i++)

inMap[inorder[i]] = i;

int preIndex = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return buildTree(preorder, inorder, 0, n - 1, preIndex, inMap);

// Inorder print to verify the constructed treevoid printInorder(Node* root) {

if (!root) return;

printInorder(root->left);

cout << root->data << " ";

printInorder(root->right);

int main() {

int preorder[] = {3, 9, 20, 15, 7};

int inorder[] = {9, 3, 15, 20, 7};

int n = sizeof(preorder) / sizeof(preorder[0]);

Node* root = buildTreeFromPreIn(preorder, inorder, n);

cout << "Inorder of constructed tree: ";

printInorder(root);

return 0;

� Code Explanation in 4 Lines:

1. Use preorder to pick the root node (starting from index 0).
2. Find the root in inorder to divide into left and right subtrees.
3. Recursively build left and right subtrees from sliced arrays.
4. Use a hashmap for fast lookup of indices in inorder to optimize.

PROBLEM:295
Question : Construct the Binary Tree from Postorder and Inorder Traversal

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


�� Construct Binary Tree from Inorder and Postorder Traversal (C++ Code)

Given:

postorder[]: Left → Right → Root

inorder[]: Left → Root → Right

The last element in postorder is always the root,


and inorder tells you the structure of the left and right subtrees.

✅ C++ Code:

cpp

#include <iostream>#include <unordered_map>using namespace std;

// Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

// Build tree using postorder and inorderNode* buildTree(int postorder[], int inorder[], int
inStart, int inEnd,

int& postIndex, unordered_map<int, int>& inMap) {

if (inStart > inEnd) return nullptr;

int rootVal = postorder[postIndex--];

Node* root = new Node(rootVal);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int inIndex = inMap[rootVal];

// IMPORTANT: build right subtree first, then left (because postorder is reversed)

root->right = buildTree(postorder, inorder, inIndex + 1, inEnd, postIndex, inMap);

root->left = buildTree(postorder, inorder, inStart, inIndex - 1, postIndex, inMap);

return root;

// Helper wrapperNode* buildTreeFromPostIn(int postorder[], int inorder[], int n) {

unordered_map<int, int> inMap;

for (int i = 0; i < n; i++)

inMap[inorder[i]] = i;

int postIndex = n - 1;

return buildTree(postorder, inorder, 0, n - 1, postIndex, inMap);

// Inorder print to verifyvoid printInorder(Node* root) {

if (!root) return;

printInorder(root->left);

cout << root->data << " ";

printInorder(root->right);

int main() {

int postorder[] = {9, 15, 7, 20, 3};

int inorder[] = {9, 3, 15, 20, 7};

int n = sizeof(postorder) / sizeof(postorder[0]);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* root = buildTreeFromPostIn(postorder, inorder, n);

cout << "Inorder of constructed tree: ";

printInorder(root);

return 0;

� Code Explanation in 4 Lines:

1. Postorder gives the root from the end, move backward.


2. Inorder helps divide tree into left and right subtrees.
3. Since postorder is left-right-root, build right subtree first.
4. Use hashmap for fast index lookup in inorder traversal.

PROBLEM:296
Question : Serialize and deserialize Binary Tree

�� Serialize and Deserialize Binary Tree — C++ Code

Serialization converts a binary tree into a string (or list)


Deserialization rebuilds the original tree from that string.

We can use preorder traversal and represent NULL nodes using a special symbol
like "N".

✅ C++ Code Using Preorder Traversal

cpp

#include <iostream>#include <sstream>#include <string>#include <queue>using namespace


std;

// Tree Nodeclass Node {public:

int data;

Node* left;

Node* right;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node(int val) {

data = val;

left = right = nullptr;

};

// � Serialize using preorder traversalvoid serialize(Node* root, stringstream &ss) {

if (!root) {

ss << "N ";

return;

ss << root->data << " ";

serialize(root->left, ss);

serialize(root->right, ss);

// � Deserialize using stringstreamNode* deserialize(stringstream &ss) {

string val;

ss >> val;

if (val == "N") return nullptr;

Node* root = new Node(stoi(val));

root->left = deserialize(ss);

root->right = deserialize(ss);

return root;

// � Print Inorder (to verify correctness)void printInorder(Node* root) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (!root) return;

printInorder(root->left);

cout << root->data << " ";

printInorder(root->right);

int main() {

// Sample tree:

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->right->left = new Node(4);

root->right->right = new Node(5);

// Serialize

stringstream ss;

serialize(root, ss);

string data = ss.str();

cout << "Serialized Tree: " << data << endl;

// Deserialize

stringstream ss2(data);

Node* newRoot = deserialize(ss2);

cout << "Inorder of Deserialized Tree: ";

printInorder(newRoot);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Explanation in 4 Lines:

1. Use preorder traversal to serialize tree into a string.


2. Represent null children with "N" to preserve structure.
3. Deserialize by reading string tokens recursively.
4. This ensures full structure is retained — even with missing nodes.

PROBLEM:297
Question : Morris Preorder Traversal of a Binary Tree

�� Morris Preorder Traversal of a Binary Tree — C++ Code (No Recursion /


No Stack)

Morris Traversal is a clever trick to traverse a binary tree using O(1) space
by creating temporary links (threads) and removing them later.

Preorder: Root → Left → Right

✅ C++ Code: Morris Preorder Traversal

cpp

#include <iostream>using namespace std;

class Node {public:

int data;

Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

void morrisPreorder(Node* root) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* curr = root;

while (curr) {

if (!curr->left) {

cout << curr->data << " ";

curr = curr->right;

} else {

Node* pred = curr->left;

// Find the rightmost node in left subtree

while (pred->right && pred->right != curr) {

pred = pred->right;

if (!pred->right) {

// Create thread and print (since it's preorder)

pred->right = curr;

cout << curr->data << " ";

curr = curr->left;

} else {

// Remove thread

pred->right = nullptr;

curr = curr->right;

int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Example tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Morris Preorder Traversal: ";

morrisPreorder(root);

return 0;

� Explanation in 4 Lines:

1. If no left child, print and move right (standard).


2. If left exists, find rightmost node (predecessor).
3. If thread not made, create thread, print node, move left.
4. If thread exists, remove it and move right.

PROBLEM:298
Question : Morris Inorder Traversal of a Binary Tree

�� Morris Inorder Traversal of a Binary Tree — C++ Code (O(1) Space)

Morris Inorder Traversal allows you to traverse a binary tree inorder


(i.e., Left → Root → Right) without recursion or stack, using threaded binary trees.

✅ C++ Code: Morris Inorder Traversal

cpp

#include <iostream>using namespace std;

class Node {public:

int data;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* left;

Node* right;

Node(int val) {

data = val;

left = right = nullptr;

};

void morrisInorder(Node* root) {

Node* curr = root;

while (curr) {

if (!curr->left) {

cout << curr->data << " ";

curr = curr->right;

} else {

Node* pred = curr->left;

// Find the inorder predecessor

while (pred->right && pred->right != curr) {

pred = pred->right;

if (!pred->right) {

// Make thread (temporary link)

pred->right = curr;

curr = curr->left;

} else {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Thread exists — restore tree and print

pred->right = nullptr;

cout << curr->data << " ";

curr = curr->right;

int main() {

// Example tree

Node* root = new Node(1);

root->left = new Node(2);

root->right = new Node(3);

root->left->left = new Node(4);

root->left->right = new Node(5);

cout << "Morris Inorder Traversal: ";

morrisInorder(root);

return 0;

� Code Explanation in 4 Lines:

1. If there’s no left child, print and move right.


2. Else, find the rightmost node in the left subtree.
3. If thread not made, make it and move left.
4. If thread exists, remove it and print, then move right.

PROBLEM:299
Question : Flatten Binary Tree to LinkedList

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Program: Flatten Binary Tree to Linked List (in-place, like a pre-order
traversal)

cpp

#include <iostream>using namespace std;

struct TreeNode {

int val;

TreeNode *left;

TreeNode *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

void flatten(TreeNode* root) {

if (!root) return;

flatten(root->left);

flatten(root->right);

TreeNode* temp = root->right;

root->right = root->left;

root->left = NULL;

TreeNode* curr = root;

while (curr->right) curr = curr->right;

curr->right = temp;

� Explanation (in 4 lines):

1. This recursively flattens left and right subtrees of the binary tree.
2. It moves the left subtree to the right and sets left to NULL.
3. Then it finds the end of the new right subtree.
4. Finally, it connects the original right subtree at the end.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Step 14 : Binary Search Trees

PROBLEM:300
Question : Introduction to Binary Search Tree

� Introduction to Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree where each node has the
following properties:

1. Left Subtree Property: All values in the left subtree of a node are smaller than
the node’s value.
2. Right Subtree Property: All values in the right subtree of a node are greater than
the node’s value.
3. No Duplicates: There are no duplicate values in the tree.

Operations on BST:

1. Insertion: Insert values by recursively finding the correct position based on


comparisons.
2. Search: Search for a value by traversing the tree, comparing values at each node.
3. Traversal: In-order traversal (left, root, right) gives values in ascending order.
4. Deletion: Deleting a node involves three cases: no children, one child, and two
children.

Benefits of BST:

 Efficient searching, insertion, and deletion with average time complexity of O(log
n) for balanced trees.

PROBLEM:301
Question : Search in a Binary Search Tree

C++ Program: Search in a Binary Search Tree (BST)

cpp

#include <iostream>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

// Function to search a value in BSTTreeNode* search(TreeNode* root, int target) {

// If root is null or we find the target

if (!root || root->val == target)

return root;

// If target is smaller, search in the left subtree

if (target < root->val)

return search(root->left, target);

// If target is larger, search in the right subtree

return search(root->right, target);

int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

// Searching for a value in the BST

int target = 7;

TreeNode* result = search(root, target);

if (result)

cout << "Found value: " << result->val << endl;

else

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Value not found!" << endl;

return 0;

� Explanation (in 4 lines):

1. The search() function recursively searches for the target value in the BST.
2. If the current node is NULL or matches the target, it returns the node.
3. If the target is smaller, it searches the left subtree; otherwise, it searches the right.
4. The main() function creates a BST and searches for the value 7, displaying the
result.

PROBLEM:302
Question : Find Min/Max in BST

� C++ Program: Find Minimum and Maximum in a Binary Search Tree (BST)

cpp

#include <iostream>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to find the minimum value in a BSTTreeNode* findMin(TreeNode* root) {

// The minimum value is the leftmost node

while (root && root->left) {

root = root->left;

return root;

// Function to find the maximum value in a BSTTreeNode* findMax(TreeNode* root) {

// The maximum value is the rightmost node

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (root && root->right) {

root = root->right;

return root;

int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

// Find and print minimum and maximum values in the BST

TreeNode* minNode = findMin(root);

TreeNode* maxNode = findMax(root);

cout << "Minimum value: " << minNode->val << endl;

cout << "Maximum value: " << maxNode->val << endl;

return 0;

� Explanation (in 4 lines):

1. The findMin() function traverses the leftmost nodes to find the minimum value.
2. The findMax() function traverses the rightmost nodes to find the maximum value.
3. In the main() function, a BST is created, and both minimum and maximum values
are found.
4. The program prints the minimum (3) and maximum (15) values of the tree.

PROBLEM:303

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Ceil in a Binary Search Tree

� C++ Program: Find Ceil in a Binary Search Tree (BST)

The Ceil of a node in a Binary Search Tree is the smallest node that is greater than
or equal to the target value.

cpp

#include <iostream>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to find the ceil of a value in a BSTTreeNode* findCeil(TreeNode* root, int target) {

TreeNode* ceil = NULL;

while (root) {

// If current node's value is greater or equal to target, it's a potential ceil

if (root->val >= target) {

ceil = root;

root = root->left; // Search for a potentially smaller ceil in the left subtree

else {

root = root->right; // Search in the right subtree as we need a larger value

return ceil;

int main() {

// Creating a simple BST

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

int target = 8;

TreeNode* ceilNode = findCeil(root, target);

if (ceilNode)

cout << "Ceil of " << target << " is: " << ceilNode->val << endl;

else

cout << "No Ceil found for " << target << endl;

return 0;

� Explanation (in 4 lines):

1. The findCeil() function traverses the tree to find the smallest node with a value
greater than or equal to the target.
2. It checks if the current node is greater than or equal to the target and stores it as
the potential ceil.
3. It then explores the left subtree to check for smaller possible ceils or the right
subtree for larger values.
4. The result is printed: for target = 8, the ceil is 10.

PROBLEM:304
Question : Floor in a Binary Search Tree

� C++ Program: Find Floor in a Binary Search Tree (BST)

The Floor of a node in a Binary Search Tree is the largest node that is smaller than
or equal to the target value.

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <iostream>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to find the floor of a value in a BSTTreeNode* findFloor(TreeNode* root, int target) {

TreeNode* floor = NULL;

while (root) {

// If current node's value is smaller or equal to target, it's a potential floor

if (root->val <= target) {

floor = root;

root = root->right; // Search for a potentially larger floor in the right subtree

else {

root = root->left; // Search in the left subtree for a smaller value

return floor;

int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int target = 8;

TreeNode* floorNode = findFloor(root, target);

if (floorNode)

cout << "Floor of " << target << " is: " << floorNode->val << endl;

else

cout << "No Floor found for " << target << endl;

return 0;

� Explanation (in 4 lines):

1. The findFloor() function traverses the BST to find the largest node with a value
smaller than or equal to the target.
2. It checks if the current node is smaller than or equal to the target and stores it as
the potential floor.
3. It then explores the right subtree to check for larger possible floors or the left
subtree for smaller values.
4. The result is printed: for target = 8, the floor is 7.

PROBLEM:305
Question : Insert a given Node in Binary Search Tree

� C++ Program: Insert a Node in a Binary Search Tree (BST)

Inserting a node into a Binary Search Tree follows the basic rule:

 If the value is smaller than the current node, insert it in the left subtree.
 If the value is greater, insert it in the right subtree.

cpp

#include <iostream>using namespace std;

struct TreeNode {

int val;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to insert a node in a BSTTreeNode* insert(TreeNode* root, int value) {

// If the root is NULL, create a new node

if (root == NULL) {

return new TreeNode(value);

// Recursively find the correct place to insert the node

if (value < root->val) {

root->left = insert(root->left, value);

} else {

root->right = insert(root->right, value);

return root;

// Function to print the inorder traversal of the BST (for testing)void inorder(TreeNode* root) {

if (root == NULL) return;

inorder(root->left);

cout << root->val << " ";

inorder(root->right);

int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


root->right = new TreeNode(15);

// Insert a new node with value 7

root = insert(root, 7);

// Print the inorder traversal to verify the insert

cout << "Inorder Traversal after insertion: ";

inorder(root); // Expected output: 5 7 10 15

cout << endl;

return 0;

� Explanation (in 4 lines):

1. The insert() function recursively finds the correct position in the BST to insert
the new value.
2. It compares the value with the current node and places it in the left or right
subtree accordingly.
3. The inorder() function is used to verify the tree structure by printing the values in
sorted order.
4. In the main() function, a new node with value 7 is inserted, and the tree's inorder
traversal is printed.

PROBLEM:306
Question : Delete a Node in Binary Search Tree

� C++ Program: Delete a Node in a Binary Search Tree (BST)

To delete a node in a Binary Search Tree, there are three possible cases:

1. Node has no children (leaf node): Simply remove the node.


2. Node has one child: Remove the node and link its parent to its child.
3. Node has two children: Find the in-order successor (or predecessor), replace
the node with that value, and then delete the successor.

cpp

#include <iostream>using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to find the minimum value node in a BSTTreeNode* findMin(TreeNode* root) {

while (root && root->left) {

root = root->left;

return root;

// Function to delete a node from a BSTTreeNode* deleteNode(TreeNode* root, int value) {

if (root == NULL) return root;

// If the value to be deleted is smaller than the root's value, go to the left subtree

if (value < root->val) {

root->left = deleteNode(root->left, value);

// If the value to be deleted is greater than the root's value, go to the right subtree

else if (value > root->val) {

root->right = deleteNode(root->right, value);

// Node to be deleted found

else {

// Case 1: Node has no child (leaf node)

if (root->left == NULL && root->right == NULL) {

delete root;

root = NULL;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Case 2: Node has one child

else if (root->left == NULL) {

TreeNode* temp = root;

root = root->right;

delete temp;

else if (root->right == NULL) {

TreeNode* temp = root;

root = root->left;

delete temp;

// Case 3: Node has two children

else {

TreeNode* temp = findMin(root->right); // Find the inorder successor

root->val = temp->val; // Copy the inorder successor's value to the current node

root->right = deleteNode(root->right, temp->val); // Delete the inorder successor

return root;

// Function to print the inorder traversal of the BST (for testing)void inorder(TreeNode* root) {

if (root == NULL) return;

inorder(root->left);

cout << root->val << " ";

inorder(root->right);

int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

cout << "Inorder Traversal before deletion: ";

inorder(root); // Expected output: 3 5 7 10 15

cout << endl;

// Deleting a node with value 5

root = deleteNode(root, 5);

cout << "Inorder Traversal after deletion: ";

inorder(root); // Expected output: 3 7 10 15

cout << endl;

return 0;

� Explanation (in 4 lines):

1. The deleteNode() function recursively finds the node to delete and handles the
three cases: no child, one child, or two children.
2. If the node has two children, it finds the in-order successor and replaces the
node's value with it, then deletes the successor.
3. The inorder() function prints the tree's values in ascending order, helping to
verify the structure.
4. In the main() function, a node with value 5 is deleted, and the tree's inorder
traversal is printed before and after the deletion.

PROBLEM:307

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Find K-th smallest/largest element in BST

� C++ Program: Find K-th Smallest and K-th Largest Element in a Binary
Search Tree (BST)

To find the K-th smallest or K-th largest element in a BST, we can perform an in-
order traversal (for smallest) or a reverse in-order traversal (for largest).

Steps to find K-th smallest:

1. Perform an in-order traversal of the BST, which gives elements in ascending


order.
2. Keep a counter during traversal, and when it reaches K, return the current node.

Steps to find K-th largest:

1. Perform a reverse in-order traversal (right subtree → node → left subtree).


2. Keep a counter during traversal, and when it reaches K, return the current node.

cpp

#include <iostream>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

int kthSmallestHelper(TreeNode* root, int& k) {

if (!root) return -1;

// Search in the left subtree

int left = kthSmallestHelper(root->left, k);

if (left != -1) return left; // If result is found in the left subtree

// Decrement k and check if we've found the k-th smallest

k--;

if (k == 0) return root->val;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Search in the right subtree

return kthSmallestHelper(root->right, k);

int kthLargestHelper(TreeNode* root, int& k) {

if (!root) return -1;

// Search in the right subtree

int right = kthLargestHelper(root->right, k);

if (right != -1) return right; // If result is found in the right subtree

// Decrement k and check if we've found the k-th largest

k--;

if (k == 0) return root->val;

// Search in the left subtree

return kthLargestHelper(root->left, k);

// Function to find k-th smallest elementint kthSmallest(TreeNode* root, int k) {

return kthSmallestHelper(root, k);

// Function to find k-th largest elementint kthLargest(TreeNode* root, int k) {

return kthLargestHelper(root, k);

int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

int k = 3;

cout << "3rd Smallest Element: " << kthSmallest(root, k) << endl; // Expected output: 7

k = 2;

cout << "2nd Largest Element: " << kthLargest(root, k) << endl; // Expected output: 10

return 0;

� Explanation (in 4 lines):

1. The kthSmallestHelper() function performs an in-order traversal, returning the K-


th smallest element.
2. The kthLargestHelper() function performs a reverse in-order traversal, returning
the K-th largest element.
3. Both functions use a counter (k) to track the K-th element and return it when
found.
4. In the main() function, the K-th smallest and K-th largest elements are printed for
a given BST.

PROBLEM:308
Question : Check if a tree is a BST or BT

� C++ Program: Check if a Tree is a Binary Search Tree (BST) or a Binary Tree
(BT)

To check if a tree is a Binary Search Tree (BST), we need to ensure that:

 For each node, all values in its left subtree are smaller
 All values in its right subtree are greater.
 This must hold recursively for all nodes in the tree.

In contrast, a Binary Tree (BT) does not have these properties; it's just a tree where
each node has at most two children.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Steps to check if a tree is a BST:

1. Perform a recursive traversal and keep track of the valid range for each node's
value.
2. If at any point a node's value violates the valid range, return false.

Code:

cpp

#include <iostream>

#include <climits>

using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to check if a tree is a BSTbool isBSTHelper(TreeNode* root, int minVal, int maxVal)
{

// An empty tree is a BST

if (root == NULL) return true;

// The current node's value must be within the valid range

if (root->val <= minVal || root->val >= maxVal) return false;

// Check the left and right subtrees recursively

return isBSTHelper(root->left, minVal, root->val) &&

isBSTHelper(root->right, root->val, maxVal);

// Function to check if a tree is a BSTbool isBST(TreeNode* root) {

return isBSTHelper(root, INT_MIN, INT_MAX);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

if (isBST(root)) {

cout << "The tree is a Binary Search Tree (BST)." << endl;

} else {

cout << "The tree is NOT a Binary Search Tree (BST)." << endl;

return 0;

� Explanation (in 4 lines):

1. The isBSTHelper() function checks if the current node’s value is within the valid
range (minVal, maxVal).
2. The range is updated as we recursively check the left and right subtrees.
3. If any node violates the BST property (value not within valid range), it returns
false.
4. The main() function checks if the tree is a BST and prints the result.

Output for this code:

For the given tree:

markdown

CopyEdit

10

/ \

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


5 15

/\

3 7

The output will be:

sql

CopyEdit

The tree is a Binary Search Tree (BST).

PROBLEM:309
Question : LCA in Binary Search Tree

� C++ Program: Lowest Common Ancestor (LCA) in a Binary Search Tree


(BST)

In a Binary Search Tree (BST), the Lowest Common Ancestor (LCA) of two
nodes n1 and n2 is defined as the deepest node that is an ancestor of both n1 and n2.

Steps to find the LCA in a BST:

If both nodes are smaller than the current node, then LCA must be in
the left subtree.

If both nodes are greater than the current node, then LCA must be in
the right subtree.

If one node is smaller and the other is larger, then the current node is
the LCA.

Code:

cpp

#include <iostream>

using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

// Function to find the LCA of two nodes in a BSTTreeNode* findLCA(TreeNode* root, int n1,
int n2) {

// Base case: if root is NULL

if (root == NULL) return NULL;

// If both n1 and n2 are smaller, LCA is in the left subtree

if (root->val > n1 && root->val > n2) {

return findLCA(root->left, n1, n2);

// If both n1 and n2 are greater, LCA is in the right subtree

if (root->val < n1 && root->val < n2) {

return findLCA(root->right, n1, n2);

// If one of n1 or n2 is smaller and the other is greater, root is the LCA

return root;

int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

int n1 = 3, n2 = 7;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


TreeNode* lca = findLCA(root, n1, n2);

if (lca) {

cout << "LCA of " << n1 << " and " << n2 << " is: " << lca->val << endl;

} else {

cout << "LCA not found!" << endl;

return 0;

Explanation (in 4 lines):

1. The findLCA() function recursively searches for the Lowest Common Ancestor in
the BST.
2. If both n1 and n2 are smaller than the current node, the LCA lies in the left subtree.
3. If both n1 and n2 are greater, the LCA lies in the right subtree.
4. If n1 and n2 lie on either side of the current node, the current node is the LCA.

Output:

For the given tree:

10

/ \

5 15

/\

3 7

If you search for the LCA of 3 and 7, the output will be:

LCA of 3 and 7 is: 5

PROBLEM:310
Question : Construct a BST from a preorder traversal

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� C++ Program: Construct a Binary Search Tree (BST) from a Preorder
Traversal

To construct a Binary Search Tree (BST) from a preorder traversal, we can follow
this strategy:

The first element in the preorder traversal is the root.

The subsequent elements are inserted into the BST as per the standard BST
insertion rules:

If an element is smaller than the current node, it will go to the left.

If it is greater, it will go to the right.

In the BST, we keep track of the valid range for each node to ensure the correct
positioning during the insertions.

Code:

cpp

#include <iostream>#include <vector>#include <climits>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to insert a node in the BST, given the value and a valid rangeTreeNode*
insertBST(TreeNode* root, int value, int minVal, int maxVal) {

// If the value is out of valid range, return NULL

if (value < minVal || value > maxVal) {

return NULL;

// Create a new node if root is NULL

if (root == NULL) {

return new TreeNode(value);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Otherwise, insert the value recursively into the left or right subtree

if (value < root->val) {

root->left = insertBST(root->left, value, minVal, root->val);

} else {

root->right = insertBST(root->right, value, root->val, maxVal);

return root;

// Function to construct a BST from a preorder traversalTreeNode*


constructBSTFromPreorder(const vector<int>& preorder) {

if (preorder.empty()) return NULL;

TreeNode* root = new TreeNode(preorder[0]);

for (int i = 1; i < preorder.size(); i++) {

root = insertBST(root, preorder[i], INT_MIN, INT_MAX);

return root;

// Function to print the inorder traversal of the BST (for testing)void inorder(TreeNode* root) {

if (root == NULL) return;

inorder(root->left);

cout << root->val << " ";

inorder(root->right);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

// Given preorder traversal

vector<int> preorder = {10, 5, 3, 7, 15};

// Construct the BST

TreeNode* root = constructBSTFromPreorder(preorder);

// Print inorder traversal of the constructed BST

cout << "Inorder Traversal of the constructed BST: ";

inorder(root); // Expected output: 3 5 7 10 15

cout << endl;

return 0;

Explanation (in 4 lines):

1. The insertBST() function inserts nodes into the BST by checking the valid range
for each node during the insertion process.
2. The constructBSTFromPreorder() function iterates through the preorder traversal
and uses insertBST() to construct the tree.
3. The inorder() function prints the inorder traversal of the constructed BST to
verify the tree structure.
4. The tree is constructed from the given preorder {10, 5, 3, 7, 15} and its inorder
traversal is printed.

Output:

For the given preorder traversal: {10, 5, 3, 7, 15}


The output will be:

Inorder Traversal of the constructed BST: 3 5 7 10 15

PROBLEM:311
Question : Inorder Successor/Predecessor in BST

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� C++ Program: Inorder Successor and Inorder Predecessor in a Binary
Search Tree (BST)

Inorder Successor:

The inorder successor of a node in a BST is the node with the smallest value that
is greater than the current node’s value. There are two cases for finding the inorder
successor:

If the node has a right child, the successor is the leftmost node of the right
subtree.

If the node does not have a right child, the successor is the lowest ancestor
for which the node is in its left subtree.

Inorder Predecessor:

The inorder predecessor of a node in a BST is the node with the largest value that
is smaller than the current node’s value. There are two cases for finding the inorder
predecessor:

If the node has a left child, the predecessor is the rightmost node of the left
subtree.

If the node does not have a left child, the predecessor is the highest ancestor
for which the node is in its right subtree.

Code:

cpp

#include <iostream>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to find the inorder successor of a given node in a BSTTreeNode*


inorderSuccessor(TreeNode* root, TreeNode* node) {

// Case 1: If the node has a right child, the successor is the leftmost node in the right subtree

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (node->right) {

TreeNode* temp = node->right;

while (temp->left) {

temp = temp->left;

return temp;

// Case 2: If no right child, go up to the first ancestor where node is in the left subtree

TreeNode* successor = NULL;

while (root) {

if (node->val < root->val) {

successor = root; // root could be the successor

root = root->left;

} else if (node->val > root->val) {

root = root->right;

} else {

break;

return successor;

// Function to find the inorder predecessor of a given node in a BSTTreeNode*


inorderPredecessor(TreeNode* root, TreeNode* node) {

// Case 1: If the node has a left child, the predecessor is the rightmost node in the left subtree

if (node->left) {

TreeNode* temp = node->left;

while (temp->right) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


temp = temp->right;

return temp;

// Case 2: If no left child, go up to the first ancestor where node is in the right subtree

TreeNode* predecessor = NULL;

while (root) {

if (node->val < root->val) {

root = root->right;

} else if (node->val > root->val) {

predecessor = root; // root could be the predecessor

root = root->left;

} else {

break;

return predecessor;

// Function to insert a node in the BST (for tree construction)TreeNode* insertBST(TreeNode*


root, int value) {

if (root == NULL) {

return new TreeNode(value);

if (value < root->val) {

root->left = insertBST(root->left, value);

} else {

root->right = insertBST(root->right, value);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return root;

int main() {

// Creating a simple BST

TreeNode* root = new TreeNode(20);

root = insertBST(root, 10);

root = insertBST(root, 30);

root = insertBST(root, 5);

root = insertBST(root, 15);

root = insertBST(root, 25);

root = insertBST(root, 35);

// Let's test the inorder successor and predecessor of node 15

TreeNode* node = root->left->right; // Node with value 15

TreeNode* successor = inorderSuccessor(root, node);

TreeNode* predecessor = inorderPredecessor(root, node);

cout << "Inorder Successor of 15: " << (successor ? successor->val : -1) << endl; //
Expected: 20

cout << "Inorder Predecessor of 15: " << (predecessor ? predecessor->val : -1) << endl; //
Expected: 10

return 0;

Explanation (in 4 lines):

1. The inorderSuccessor() function handles two cases: if the node has a right child
(find the leftmost node of the right subtree) or if it doesn't (find the lowest ancestor for
which the node is in its left subtree).

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2. The inorderPredecessor() function works similarly by checking if the node has a
left child (find the rightmost node of the left subtree) or if it doesn't (find the highest
ancestor for which the node is in its right subtree).
3. The insertBST() function is used to create the BST for testing.
4. In the main() function, we find the inorder successor and predecessor for the
node with value 15 and print their values.

Output:

For the tree:

20

/ \

10 30

/ \ / \

5 15 25 35

For the node 15:

Inorder Successor of 15: 20Inorder Predecessor of 15: 10

PROBLEM:312
Question : Merge 2 BST's

� C++ Program: Merge Two Binary Search Trees (BSTs)

To merge two BSTs, we need to combine the elements of both trees and create a
new BST with these elements while maintaining the BST properties.

Steps to merge two BSTs:

1. Inorder Traversal: Perform an inorder traversal on both BSTs to get two sorted
arrays of the elements.
2. Merge the Arrays: Use the two sorted arrays to create a new sorted array.
3. Construct a New BST: Use the merged sorted array to build a new BST.

Code:

cpp

#include <iostream>#include <vector>using namespace std;

struct TreeNode {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Inorder traversal to store elements of a BST into a vectorvoid inorder(TreeNode* root,


vector<int>& result) {

if (root == NULL) return;

inorder(root->left, result);

result.push_back(root->val);

inorder(root->right, result);

// Function to merge two sorted arrays into a single sorted arrayvector<int>


mergeSortedArrays(const vector<int>& arr1, const vector<int>& arr2) {

vector<int> merged;

int i = 0, j = 0;

// Merge the arrays

while (i < arr1.size() && j < arr2.size()) {

if (arr1[i] < arr2[j]) {

merged.push_back(arr1[i]);

i++;

} else {

merged.push_back(arr2[j]);

j++;

// If elements left in arr1

while (i < arr1.size()) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


merged.push_back(arr1[i]);

i++;

// If elements left in arr2

while (j < arr2.size()) {

merged.push_back(arr2[j]);

j++;

return merged;

// Function to construct a BST from a sorted arrayTreeNode* sortedArrayToBST(const


vector<int>& arr, int start, int end) {

if (start > end) return NULL;

// Middle element to maintain balanced tree

int mid = (start + end) / 2;

TreeNode* root = new TreeNode(arr[mid]);

// Recursively build the left and right subtrees

root->left = sortedArrayToBST(arr, start, mid - 1);

root->right = sortedArrayToBST(arr, mid + 1, end);

return root;

// Function to merge two BSTsTreeNode* mergeBSTs(TreeNode* root1, TreeNode* root2) {

// Step 1: Store the inorder traversal of both trees in arrays

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<int> inorder1, inorder2;

inorder(root1, inorder1);

inorder(root2, inorder2);

// Step 2: Merge the two sorted arrays

vector<int> merged = mergeSortedArrays(inorder1, inorder2);

// Step 3: Build a new BST from the merged sorted array

return sortedArrayToBST(merged, 0, merged.size() - 1);

// Function to print the inorder traversal of the BST (for testing)void inorderTraversal(TreeNode*
root) {

if (root == NULL) return;

inorderTraversal(root->left);

cout << root->val << " ";

inorderTraversal(root->right);

int main() {

// Construct first BST

TreeNode* root1 = new TreeNode(10);

root1->left = new TreeNode(5);

root1->right = new TreeNode(15);

root1->left->left = new TreeNode(3);

root1->left->right = new TreeNode(7);

// Construct second BST

TreeNode* root2 = new TreeNode(12);

root2->left = new TreeNode(8);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


root2->right = new TreeNode(18);

root2->left->left = new TreeNode(6);

root2->left->right = new TreeNode(9);

// Merge the two BSTs

TreeNode* mergedRoot = mergeBSTs(root1, root2);

// Print the inorder traversal of the merged BST

cout << "Inorder traversal of the merged BST: ";

inorderTraversal(mergedRoot); // Expected: 3 5 6 7 8 9 10 12 15 18

cout << endl;

return 0;

Explanation (in 4 lines):

1. The inorder() function performs an inorder traversal of each BST and stores the
result in a vector.
2. The mergeSortedArrays() function merges the two sorted arrays from the inorder
traversals into one sorted array.
3. The sortedArrayToBST() function constructs a new BST from the merged sorted
array while maintaining balance by choosing the middle element as the root.
4. The mergeBSTs() function calls the above helper functions to merge two BSTs and
return the new merged BST.

Output:

For the two BSTs:

10 12

/ \ / \

5 15 8 18

/\ / \

3 7 6 9

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The output will be:

Inorder traversal of the merged BST: 3 5 6 7 8 9 10 12 15 18

PROBLEM:313
Question : Two Sum In BST | Check if there exists a pair with Sum K

� C++ Program: Two Sum in a Binary Search Tree (BST)

The task is to check whether there exists a pair of nodes in a BST such that the sum
of their values equals a given number K.

Approach:

1. Inorder Traversal: Since the tree is a BST, an inorder traversal will


produce a sorted list of the node values.
2. Two-pointer technique: After obtaining the sorted list of values, use the
two-pointer technique to find if there exists a pair of elements whose sum is
equal to K:

One pointer starts from the beginning of the list and the other from the
end.

If the sum of the two elements is equal to K, we return true.

If the sum is less than K, move the left pointer to the right to increase
the sum.

If the sum is greater than K, move the right pointer to the left to
decrease the sum.

Code:

cpp

#include <iostream>#include <vector>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Inorder traversal to store elements of a BST into a vectorvoid inorder(TreeNode* root,
vector<int>& result) {

if (root == NULL) return;

inorder(root->left, result);

result.push_back(root->val);

inorder(root->right, result);

// Function to check if there exists a pair with sum K in the BSTbool


findPairWithSumK(TreeNode* root, int K) {

// Step 1: Get the inorder traversal of the BST

vector<int> inorderList;

inorder(root, inorderList);

// Step 2: Use two pointers to find if there exists a pair whose sum is K

int left = 0, right = inorderList.size() - 1;

while (left < right) {

int currentSum = inorderList[left] + inorderList[right];

if (currentSum == K) {

return true; // Found the pair

} else if (currentSum < K) {

left++; // Move the left pointer to the right to increase the sum

} else {

right--; // Move the right pointer to the left to decrease the sum

return false; // No pair found

// Function to insert a node in the BSTTreeNode* insertBST(TreeNode* root, int value) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (root == NULL) {

return new TreeNode(value);

if (value < root->val) {

root->left = insertBST(root->left, value);

} else {

root->right = insertBST(root->right, value);

return root;

int main() {

// Constructing a simple BST

TreeNode* root = new TreeNode(10);

root = insertBST(root, 5);

root = insertBST(root, 15);

root = insertBST(root, 3);

root = insertBST(root, 7);

// Check if a pair exists with sum K

int K = 12;

if (findPairWithSumK(root, K)) {

cout << "A pair with sum " << K << " exists in the BST." << endl;

} else {

cout << "No pair with sum " << K << " exists in the BST." << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Explanation (in 4 lines):

1. The inorder() function performs an inorder traversal of the BST, storing the node
values in a sorted array.
2. The findPairWithSumK() function uses the two-pointer technique to check if there
exists a pair of elements in the sorted array that sums to K.
3. The insertBST() function is used to construct the BST for testing.
4. In the main() function, we check if a pair with the sum K exists in the BST and
print the result.

Output:

For the BST:

10

/ \

5 15

/\

3 7

If the sum K is 12, the output will be:

A pair with sum 12 exists in the BST.

This confirms that the pair (5, 7) has the sum 12.

PROBLEM:314
Question : Recover BST | Correct BST with two nodes swapped

� C++ Program: Recover a Binary Search Tree (BST) with Two Nodes
Swapped

In this problem, we are given a Binary Search Tree (BST) where two nodes have
been swapped by mistake. The task is to recover the BST and fix the swapped
nodes.

Approach:

1.Inorder Traversal: The inorder traversal of a BST produces a sorted array. If two
nodes are swapped, the inorder traversal will no longer be sorted. We need to find
where the sorted order breaks.

2.Identify the swapped nodes:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


During the inorder traversal, find two nodes that are out of order:

The first node that is larger than its next node is the first swapped node.

The second node that is smaller than its previous node is the second
swapped node.

Swap the nodes back: Once the two misplaced nodes are found, swap their
values to restore the BST.

Code:

cpp

#include <iostream>#include <vector>#include <climits>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

// Function to perform inorder traversal and store the result in a vectorvoid inorder(TreeNode*
root, vector<TreeNode*>& result) {

if (root == NULL) return;

inorder(root->left, result);

result.push_back(root);

inorder(root->right, result);

// Function to recover the BSTvoid recoverBST(TreeNode* root) {

// Step 1: Perform inorder traversal to get the nodes in sorted order

vector<TreeNode*> inorderList;

inorder(root, inorderList);

TreeNode* first = NULL;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


TreeNode* second = NULL;

// Step 2: Identify the two nodes that are swapped

for (int i = 0; i < inorderList.size() - 1; i++) {

if (inorderList[i]->val > inorderList[i + 1]->val) {

// The first node is the previous node where the order breaks

if (!first) {

first = inorderList[i];

// The second node is the current node where the order breaks

second = inorderList[i + 1];

// Step 3: If both nodes are found, swap their values

if (first && second) {

swap(first->val, second->val);

// Function to insert a node in the BST (for tree construction)TreeNode* insertBST(TreeNode*


root, int value) {

if (root == NULL) {

return new TreeNode(value);

if (value < root->val) {

root->left = insertBST(root->left, value);

} else {

root->right = insertBST(root->right, value);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return root;

// Function to print inorder traversal of the BST (for testing)void inorderTraversal(TreeNode*


root) {

if (root == NULL) return;

inorderTraversal(root->left);

cout << root->val << " ";

inorderTraversal(root->right);

int main() {

// Construct a BST where two nodes are swapped

TreeNode* root = new TreeNode(10);

root = insertBST(root, 5);

root = insertBST(root, 15);

root = insertBST(root, 3);

root = insertBST(root, 7);

root = insertBST(root, 12);

root = insertBST(root, 20);

// After construction, swap two nodes manually for testing

swap(root->left->val, root->right->val); // Swap nodes 5 and 15

cout << "Inorder traversal before recovery: ";

inorderTraversal(root);

cout << endl;

// Recover the BST

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


recoverBST(root);

cout << "Inorder traversal after recovery: ";

inorderTraversal(root);

cout << endl;

return 0;

Explanation (in 4 lines):

1. The inorder() function traverses the tree in-order and stores the nodes in a
vector.
2. The recoverBST() function identifies the two swapped nodes by checking where
the inorder traversal is not sorted, then swaps them to restore the BST.
3. The insertBST() function is used to construct a BST for testing, and two nodes
are manually swapped to simulate the problem.
4. The inorderTraversal() function prints the tree before and after recovery to
verify the correction.

Output:

Given the original BST:

10

/ \

5 15

/\ \

3 7 20

12

After swapping nodes 5 and 15, the tree becomes:

10

/ \

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


15 5

/\ \

3 7 20

12

The program will print:

Inorder traversal before recovery: 15 3 7 10 5 12 20 Inorder traversal after recovery: 3 5 7 10 12


15 20

This confirms that the tree was recovered correctly by swapping back the misplaced
nodes

PROBLEM:315
Question : Largest BST in Binary Tree

� C++ Program: Largest BST in a Binary Tree

In this problem, we are given a binary tree, and we need to find the largest Binary
Search Tree (BST) in it. The goal is to find the size of the largest BST subtree in the
binary tree.

Approach:

1. Postorder Traversal: Perform a postorder traversal to process each node. For


each node, determine if its subtree forms a BST.
2. Check if BST: For each node, check if the subtree rooted at that node is a valid
BST by ensuring:

The left subtree is a BST.

The right subtree is a BST.

The node’s value is greater than the maximum value in the left subtree and
less than the minimum value in the right subtree.

3.Track Size: While traversing, maintain the size of the largest BST found so far.

Code:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>#include <climits>using namespace std;

struct TreeNode {

int val;

TreeNode *left, *right;

TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

struct SubtreeInfo {

bool isBST;

int size;

int minVal;

int maxVal;

};

// Function to perform postorder traversal and find the largest BST in the binary treeSubtreeInfo
largestBSTInTree(TreeNode* root) {

// Base case: If the node is null, it's a valid BST with size 0

if (root == NULL) {

return {true, 0, INT_MAX, INT_MIN};

// Recursively get the information from left and right subtrees

SubtreeInfo left = largestBSTInTree(root->left);

SubtreeInfo right = largestBSTInTree(root->right);

// Current node's subtree is a BST if:

// 1. Left subtree is a BST

// 2. Right subtree is a BST

// 3. Root's value is greater than the max value in left subtree and less than the min value in
right subtree

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (left.isBST && right.isBST && root->val > left.maxVal && root->val < right.minVal) {

// Current node's subtree is a valid BST, calculate its size

int size = 1 + left.size + right.size;

return {true, size, min(root->val, left.minVal), max(root->val, right.maxVal)};

// If the current subtree is not a BST, return the largest BST size from its children

return {false, max(left.size, right.size), INT_MIN, INT_MAX};

// Function to insert a node in the binary tree (for tree construction)TreeNode* insert(TreeNode*
root, int value) {

if (root == NULL) {

return new TreeNode(value);

if (value < root->val) {

root->left = insert(root->left, value);

} else {

root->right = insert(root->right, value);

return root;

int main() {

// Constructing a binary tree

TreeNode* root = new TreeNode(10);

root = insert(root, 5);

root = insert(root, 1);

root = insert(root, 8);

root = insert(root, 7);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


root = insert(root, 15);

root = insert(root, 12);

root = insert(root, 20);

// Find the largest BST in the binary tree

SubtreeInfo result = largestBSTInTree(root);

// Print the size of the largest BST

cout << "Size of the largest BST in the binary tree: " << result.size << endl;

return 0;

Explanation (in 4 lines):

1. The largestBSTInTree() function uses postorder traversal to check each subtree


and determine if it's a BST by comparing the node values with the min and max
values of the left and right subtrees.
2. If the current subtree is a valid BST, its size is calculated as the sum of the left
and right subtree sizes plus one for the current node.
3. The SubtreeInfo structure keeps track of whether a subtree is a BST, its size,
and the min and max values for efficient comparison.
4. The insert() function is used to construct the binary tree for testing, and the
result is the size of the largest BST found.

Output:

For the tree:

10

/ \

5 15

/\ / \

1 8 12 20

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


7

The largest BST is the subtree rooted at node 12 with size 3. The output will be:

Size of the largest BST in the binary tree: 3

This confirms that the largest BST in the tree is the one rooted at 12, which has 3
nodes (12, 15, 20).

Step 15 : Graphs

PROBLEM:316
Question : Graph and Types

� Introduction to Graphs and Their Types (with C++ Code)

A Graph is a non-linear data structure consisting of nodes (also called vertices) and
edges that connect pairs of nodes. Graphs are widely used to represent networks
like social networks, road maps, web pages, etc.

� Graph Terminology

Vertex (Node): A fundamental part of a graph.

Edge: A connection between two vertices.

Adjacency List: Stores a list of neighbors for each vertex.

Adjacency Matrix: A 2D array to represent connections.

Directed Graph (DiGraph): Edges have direction (A → B).

Undirected Graph: Edges have no direction (A — B).

Weighted Graph: Edges have weights (cost, distance, etc.).

Unweighted Graph: Edges do not have weights.

Types of Graphs

Directed Graph

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Undirected Graph

Weighted Graph

Unweighted Graph

Cyclic / Acyclic Graph

Connected / Disconnected Graph

Tree (special type of graph)

DAG (Directed Acyclic Graph)

C++ Code to Represent a Graph Using Adjacency List

cpp

#include <iostream>#include <vector>using namespace std;

class Graph {

public:

int V; // Number of vertices

vector<vector<int>> adj; // Adjacency list

Graph(int V) {

this->V = V;

adj.resize(V);

// Add edge (undirected by default)

void addEdge(int u, int v) {

adj[u].push_back(v);

adj[v].push_back(u); // remove this line for directed graph

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Display graph

void printGraph() {

for (int i = 0; i < V; ++i) {

cout << "Vertex " << i << " -> ";

for (int j : adj[i]) {

cout << j << " ";

cout << endl;

};

int main() {

Graph g(5); // Create a graph with 5 vertices

g.addEdge(0, 1);

g.addEdge(0, 4);

g.addEdge(1, 2);

g.addEdge(1, 3);

g.addEdge(1, 4);

g.addEdge(2, 3);

g.addEdge(3, 4);

cout << "Adjacency List of the Graph:\n";

g.printGraph();

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

Explanation (in 4 lines):

1. A Graph class is created with an adjacency list representation.


2. The addEdge() function adds edges between nodes; undirected edges are added
both ways.
3. The printGraph() function prints neighbors of each vertex.
4. The main() function constructs a simple graph and displays its adjacency list.

PROBLEM:317
Question : Graph Representation | C++

� Graph Representation in C++

Graphs can be represented in two main ways in C++:

Adjacency Matrix

Adjacency List

✅ 1. Adjacency Matrix

A 2D array of size V x V (where V is the number of vertices).

matrix[i][j] = 1 means there is an edge from vertex i to vertex j.

cpp

#include <iostream>using namespace std;

void adjacencyMatrix(int V) {

int matrix[5][5] = {0}; // Initialize 5x5 matrix with 0s

// Add some edges

matrix[0][1] = 1;

matrix[1][2] = 1;

matrix[2][0] = 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Print matrix

cout << "Adjacency Matrix:\n";

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

cout << matrix[i][j] << " ";

cout << endl;

int main() {

int V = 5;

adjacencyMatrix(V);

return 0;

✅ 2. Adjacency List

Each vertex stores a list of its neighbors.

More space-efficient for sparse graphs.

cpp

#include <iostream>#include <vector>using namespace std;

class Graph {

public:

int V;

vector<vector<int>> adj;

Graph(int V) {

this->V = V;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


adj.resize(V);

void addEdge(int u, int v) {

adj[u].push_back(v);

adj[v].push_back(u); // Remove for directed graph

void printList() {

cout << "Adjacency List:\n";

for (int i = 0; i < V; ++i) {

cout << i << " -> ";

for (int node : adj[i])

cout << node << " ";

cout << endl;

};

int main() {

Graph g(5);

g.addEdge(0, 1);

g.addEdge(1, 2);

g.addEdge(2, 3);

g.addEdge(3, 4);

g.printList();

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Explanation (in 4 lines):

1. Adjacency Matrix uses a 2D array where each cell (i, j) tells if there's an edge
between i and j.
2. Adjacency List uses a vector of vectors to store neighbors for each vertex,
saving space in sparse graphs.
3. addEdge() connects nodes, and printList() displays connections for each vertex.
4. Use adjacency matrix for dense graphs, adjacency list for sparse graphs.

PROBLEM:318
Question : Graph Representation | Java

� Graph Representation in Java

Graphs in Java are typically represented using two main structures:

Adjacency Matrix

Adjacency List

Let’s see both implementations using Java.

✅ 1. Adjacency Matrix (Java)

java

public class GraphMatrix {

public static void main(String[] args) {

int V = 5;

int[][] adjMatrix = new int[V][V];

// Add edges

adjMatrix[0][1] = 1;

adjMatrix[1][2] = 1;

adjMatrix[2][3] = 1;

adjMatrix[3][4] = 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Print matrix

System.out.println("Adjacency Matrix:");

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

System.out.print(adjMatrix[i][j] + " ");

System.out.println();

✅ 2. Adjacency List (Java)

java

CopyEdit

import java.util.*;

public class GraphList {

int V;

List<List<Integer>> adjList;

GraphList(int V) {

this.V = V;

adjList = new ArrayList<>();

for (int i = 0; i < V; i++)

adjList.add(new ArrayList<>());

void addEdge(int u, int v) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


adjList.get(u).add(v);

adjList.get(v).add(u); // Remove for directed graph

void printGraph() {

System.out.println("Adjacency List:");

for (int i = 0; i < V; i++) {

System.out.print(i + " -> ");

for (int node : adjList.get(i))

System.out.print(node + " ");

System.out.println();

public static void main(String[] args) {

GraphList g = new GraphList(5);

g.addEdge(0, 1);

g.addEdge(1, 2);

g.addEdge(2, 3);

g.addEdge(3, 4);

g.printGraph();

� Explanation (in 4 lines):

1. Adjacency Matrix: A 2D array where matrix[i][j] = 1 means an edge from i to


j

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2. Adjacency List: Uses an array of lists to store neighbors, efficient for sparse
graphs.
3. addEdge() connects nodes; undirected edges are stored both ways.
4. The printGraph() method displays all connected nodes for each vertex.

PROBLEM:319
Question : Connected Components | Logic Explanation

� Connected Components – Logic Explanation (Graph Theory)

In graph theory, a Connected Component is a set of vertices where:

There is a path between every pair of nodes in the component.

No node in the component is connected to any node outside the component.

� Types Based on Graph

In an undirected graph, components are simple to find.

In a directed graph, we use Strongly Connected Components (SCC).

✅ Key Logic to Find Connected Components

We use DFS (Depth First Search) or BFS (Breadth First Search) to find
connected components in a graph.

Step-by-Step Logic:

Maintain a visited array to track visited nodes.

Loop through all vertices:

If a node is not visited, start a DFS/BFS from it.

All nodes reached from that start node form one connected
component.

Repeat until all nodes are visited.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The number of times you start DFS/BFS = Number of connected
components.

� Example:

For this graph:

0—1 2—3

Connected components: [0, 1], [2, 3]

We do:

DFS from 0 → marks 0 and 1

DFS from 2 → marks 2 and 3


→ Total components = 2

⚙️ Summary (in 4 lines):

1. A connected component includes all nodes that are connected via some path.
2. Use DFS or BFS to explore nodes from an unvisited vertex.
3. Each new DFS/BFS marks a separate component.
4. The number of times DFS/BFS runs = number of connected components

PROBLEM:320
Question : BFS

� Breadth-First Search (BFS) – Explanation & C++ Code

BFS (Breadth-First Search) is a graph traversal algorithm that explores nodes level
by level starting from a given source node. It is implemented using a queue.

✅ BFS Logic (Step-by-Step):

1. Start from the source node, mark it visited, and enqueue it.
2. While the queue is not empty:

Dequeue the front node.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Visit all its unvisited neighbors, mark them visited, and enqueue them.

Repeat until all reachable nodes are visited

� C++ Code for BFS on an Undirected Graph

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class Graph {public:

int V;

vector<vector<int>> adj;

Graph(int V) {

this->V = V;

adj.resize(V);

void addEdge(int u, int v) {

adj[u].push_back(v);

adj[v].push_back(u); // remove for directed graph

void bfs(int start) {

vector<bool> visited(V, false);

queue<int> q;

visited[start] = true;

q.push(start);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "BFS Traversal starting from node " << start << ": ";

while (!q.empty()) {

int node = q.front();

q.pop();

cout << node << " ";

for (int neighbor : adj[node]) {

if (!visited[neighbor]) {

visited[neighbor] = true;

q.push(neighbor);

cout << endl;

};

int main() {

Graph g(6);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 3);

g.addEdge(2, 4);

g.addEdge(4, 5);

g.bfs(0); // Starting BFS from node 0

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Explanation (in 4 lines):

1. BFS starts from a node, visits all its direct neighbors before going deeper.
2. A queue is used to keep track of the nodes to be visited next.
3. A visited array prevents revisiting the same node.
4. It is ideal for finding the shortest path in unweighted graphs.

PROBLEM:321
Question : DFS

� Depth-First Search (DFS) – Explanation & C++ Code

DFS (Depth-First Search) is a graph traversal technique that explores as far as


possible along each branch before backtracking. It is implemented recursively or
using a stack.

✅ DFS Logic (Step-by-Step):

1. Start from a source node.


2. Mark the current node visited.
3. Recursively visit all its unvisited neighbors.
4. Continue until all reachable nodes are visited.

� C++ Code for DFS on an Undirected Graph

cpp

#include <iostream>#include <vector>using namespace std;

class Graph {public:

int V;

vector<vector<int>> adj;

Graph(int V) {

this->V = V;

adj.resize(V);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

void addEdge(int u, int v) {

adj[u].push_back(v);

adj[v].push_back(u); // Remove for directed graph

void dfsUtil(int node, vector<bool>& visited) {

visited[node] = true;

cout << node << " ";

for (int neighbor : adj[node]) {

if (!visited[neighbor]) {

dfsUtil(neighbor, visited);

void dfs(int start) {

vector<bool> visited(V, false);

cout << "DFS Traversal starting from node " << start << ": ";

dfsUtil(start, visited);

cout << endl;

};

int main() {

Graph g(6);

g.addEdge(0, 1);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


g.addEdge(0, 2);

g.addEdge(1, 3);

g.addEdge(2, 4);

g.addEdge(4, 5);

g.dfs(0); // Starting DFS from node 0

return 0;

� Explanation (in 4 lines):

1. DFS explores a node and recursively visits all its unvisited neighbors.
2. A visited array is used to avoid revisiting the same node.
3. It goes deep into a branch before moving to the next.
4. Ideal for exploring connected components or detecting cycles.

PROBLEM:322
Question : Number of provinces (leetcode)

DFS-Based C++ Solution

cpp

#include <iostream>#include <vector>using namespace std;

class Solution {public:

void dfs(int node, vector<vector<int>>& isConnected, vector<bool>& visited) {

visited[node] = true;

for (int j = 0; j < isConnected.size(); ++j) {

if (isConnected[node][j] == 1 && !visited[j]) {

dfs(j, isConnected, visited);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int findCircleNum(vector<vector<int>>& isConnected) {

int n = isConnected.size();

vector<bool> visited(n, false);

int provinces = 0;

for (int i = 0; i < n; ++i) {

if (!visited[i]) {

dfs(i, isConnected, visited);

provinces++;

return provinces;

};

// Driver Codeint main() {

Solution sol;

vector<vector<int>> isConnected = {

{1, 1, 0},

{1, 1, 0},

{0, 0, 1}

};

cout << "Number of Provinces: " << sol.findCircleNum(isConnected) << endl;

return 0;

� Explanation (in 4 lines):

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. Treat each city as a node; isConnected[i][j] == 1 means there’s an edge.
2. Use DFS to visit all cities in a connected group (province).
3. For each unvisited city, start a new DFS and count it as a province.
4. Return the total number of DFS runs = number of provinces.

PROBLEM:323
Question : Connected Components Problem in Matrix

� Connected Components in a Matrix (DFS/BFS Based Grid Problem)

This is a classic grid traversal problem where each cell is treated like a node in a
graph. You're often asked to count connected groups (components) of 1s (or specific
characters).

✅ Problem Example:

Given a 2D matrix of 0s and 1s, count the number of connected components of


1s.

Cells are connected 4-directionally (up, down, left, right).

� Sample Input:

grid = {

{1, 1, 0, 0},

{0, 1, 0, 0},

{1, 0, 1, 1},

{0, 0, 1, 1}

Output: 2 → Two connected components of 1s.

✅ C++ Code Using DFS

cpp

#include <iostream>#include <vector>using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


class Solution {public:

void dfs(int i, int j, vector<vector<int>>& grid, vector<vector<bool>>& visited) {

int rows = grid.size();

int cols = grid[0].size();

if (i < 0 || j < 0 || i >= rows || j >= cols) return;

if (grid[i][j] == 0 || visited[i][j]) return;

visited[i][j] = true;

// 4 directions

dfs(i+1, j, grid, visited);

dfs(i-1, j, grid, visited);

dfs(i, j+1, grid, visited);

dfs(i, j-1, grid, visited);

int countComponents(vector<vector<int>>& grid) {

int rows = grid.size(), cols = grid[0].size();

vector<vector<bool>> visited(rows, vector<bool>(cols, false));

int count = 0;

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < cols; ++j) {

if (grid[i][j] == 1 && !visited[i][j]) {

dfs(i, j, grid, visited);

count++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return count;

};

// Driver codeint main() {

vector<vector<int>> grid = {

{1, 1, 0, 0},

{0, 1, 0, 0},

{1, 0, 1, 1},

{0, 0, 1, 1}

};

Solution sol;

cout << "Connected Components of 1s: " << sol.countComponents(grid) << endl;

return 0;

� Explanation (in 4 lines):

1. Treat each 1 as a node; use DFS to explore all 1s connected to it.


2. For every unvisited 1, run DFS to mark the entire component.
3. Count how many times DFS is initiated – that’s your number of components.
4. A visited matrix ensures nodes aren’t visited more than once.

PROBLEM:324
Question : Rotten Oranges

� Problem Summary:

You're given a 2D grid:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


0 → empty cell

1 → fresh orange

2 → rotten orange

Every minute, a rotten orange makes its adjacent (4-directionally) fresh oranges
rotten.
Return the minimum minutes needed for all oranges to become rotten.
If it's impossible, return -1.

✅ C++ Code using BFS

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class Solution {public:

int orangesRotting(vector<vector<int>>& grid) {

int rows = grid.size();

int cols = grid[0].size();

queue<pair<int, int>> q;

int fresh = 0, time = 0;

// Step 1: Put all rotten oranges in queue

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < cols; ++j) {

if (grid[i][j] == 2)

q.push({i, j});

else if (grid[i][j] == 1)

fresh++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// 4 directions

vector<pair<int, int>> dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}};

// Step 2: BFS from rotten oranges

while (!q.empty() && fresh > 0) {

int size = q.size();

time++;

for (int i = 0; i < size; ++i) {

auto [x, y] = q.front(); q.pop();

for (auto [dx, dy] : dirs) {

int nx = x + dx, ny = y + dy;

if (nx >= 0 && ny >= 0 && nx < rows && ny < cols && grid[nx][ny] == 1) {

grid[nx][ny] = 2;

fresh--;

q.push({nx, ny});

return (fresh == 0) ? time : -1;

};

// Driver Codeint main() {

vector<vector<int>> grid = {

{2,1,1},

{1,1,0},

{0,1,1}

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

Solution sol;

cout << "Minutes to rot all oranges: " << sol.orangesRotting(grid) << endl;

return 0;

� Explanation (in 4 lines):

1. Push all initially rotten oranges into a queue.


2. Use BFS to spread rotting level by level (minute by minute).
3. For each fresh orange turned rotten, decrement fresh count.
4. If all oranges rot, return time; else, return -1

PROBLEM:325
Question : Flood fill

C++ Code Using DFS

cpp

#include <iostream>#include <vector>using namespace std;

class Solution {public:

void dfs(vector<vector<int>>& image, int i, int j, int color, int newColor) {

int rows = image.size();

int cols = image[0].size();

if (i < 0 || j < 0 || i >= rows || j >= cols || image[i][j] != color)

return;

image[i][j] = newColor;

dfs(image, i+1, j, color, newColor);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


dfs(image, i-1, j, color, newColor);

dfs(image, i, j+1, color, newColor);

dfs(image, i, j-1, color, newColor);

vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {

int startColor = image[sr][sc];

if (startColor != newColor)

dfs(image, sr, sc, startColor, newColor);

return image;

};

// Driver codeint main() {

vector<vector<int>> image = {

{1, 1, 1},

{1, 1, 0},

{1, 0, 1}

};

int sr = 1, sc = 1, newColor = 2;

Solution sol;

vector<vector<int>> result = sol.floodFill(image, sr, sc, newColor);

cout << "Flood filled image:\n";

for (auto row : result) {

for (int pixel : row)

cout << pixel << " ";

cout << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return 0;

� Explanation (in 4 lines):

1.Store the startColor of the pixel and avoid replacing with the same color.

2.Use DFS to visit all 4-directionally connected pixels with startColor.

3.Change each visited pixel to newColor.

4.Return the modified image.

PROBLEM:326
Question : Cycle Detection in unirected Graph (bfs)

� Cycle Detection in an Undirected Graph using BFS

Detecting a cycle in an undirected graph can be done using Breadth-First Search


(BFS) by keeping track of parent nodes while traversing.

� Key Idea:

 In BFS, if we visit a neighbor that is already visited and is not the parent, then
a cycle exists.

✅ C++ Code (Using BFS)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class Graph {

int V;

vector<vector<int>> adj;

public:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Graph(int V) {

this->V = V;

adj.resize(V);

void addEdge(int u, int v) {

adj[u].push_back(v);

adj[v].push_back(u); // Undirected graph

bool hasCycleBFS(int start, vector<bool>& visited) {

queue<pair<int, int>> q; // {node, parent}

visited[start] = true;

q.push({start, -1});

while (!q.empty()) {

int node = q.front().first;

int parent = q.front().second;

q.pop();

for (int neighbor : adj[node]) {

if (!visited[neighbor]) {

visited[neighbor] = true;

q.push({neighbor, node});

} else if (neighbor != parent) {

return true; // Cycle detected

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return false;

bool hasCycle() {

vector<bool> visited(V, false);

for (int i = 0; i < V; i++) {

if (!visited[i]) {

if (hasCycleBFS(i, visited)) return true;

return false;

};

// Driver Codeint main() {

Graph g(5);

g.addEdge(0, 1);

g.addEdge(1, 2);

g.addEdge(2, 3);

g.addEdge(3, 4);

g.addEdge(4, 1); // This edge creates a cycle

if (g.hasCycle())

cout << "Cycle detected in the graph.\n";

else

cout << "No cycle found.\n";

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Explanation (in 4 lines):

1. Traverse each component using BFS while tracking each node’s parent.
2. If a neighbor is already visited and it's not the parent, a cycle is found.
3. Check every component in case the graph is disconnected.
4. If no such condition is met, the graph is acyclic.

PROBLEM:327
Question : Cycle Detection in undirected Graph (dfs)

� Cycle Detection in an Undirected Graph using DFS

� Core Idea:

In an undirected graph, a cycle exists if we visit an already visited node that is not
the parent of the current node during a DFS traversal.

✅ C++ Code using DFS

cpp

#include <iostream>#include <vector>using namespace std;

class Graph {

int V;

vector<vector<int>> adj;

public:

Graph(int V) {

this->V = V;

adj.resize(V);

void addEdge(int u, int v) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


adj[u].push_back(v);

adj[v].push_back(u); // Undirected graph

bool dfs(int node, int parent, vector<bool>& visited) {

visited[node] = true;

for (int neighbor : adj[node]) {

if (!visited[neighbor]) {

if (dfs(neighbor, node, visited))

return true;

} else if (neighbor != parent) {

return true; // Cycle found

return false;

bool hasCycle() {

vector<bool> visited(V, false);

for (int i = 0; i < V; i++) {

if (!visited[i]) {

if (dfs(i, -1, visited))

return true;

return false;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

};

// Driver Codeint main() {

Graph g(5);

g.addEdge(0, 1);

g.addEdge(1, 2);

g.addEdge(2, 3);

g.addEdge(3, 4);

g.addEdge(4, 1); // This creates a cycle

if (g.hasCycle())

cout << "Cycle detected in the graph.\n";

else

cout << "No cycle found.\n";

return 0;

� Explanation (in 4 lines):

1. Start DFS and mark nodes as visited.


2. For each neighbor, if it’s unvisited, recurse with node as its parent.
3. If it’s visited and not the parent, then a cycle exists.
4. Apply this logic to all components of the graph.

PROBLEM:328
Question : 0/1 Matrix (Bfs Problem)

C++ Code (Using BFS from all 0s)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


class Solution {public:

vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {

int rows = mat.size();

int cols = mat[0].size();

queue<pair<int, int>> q;

// Initialize distance matrix and queue with 0s

vector<vector<int>> dist(rows, vector<int>(cols, INT_MAX));

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < cols; ++j) {

if (mat[i][j] == 0) {

dist[i][j] = 0;

q.push({i, j});

vector<pair<int, int>> dirs = {{0,1},{1,0},{0,-1},{-1,0}};

// BFS from all 0s

while (!q.empty()) {

auto [x, y] = q.front(); q.pop();

for (auto [dx, dy] : dirs) {

int nx = x + dx, ny = y + dy;

if (nx >= 0 && ny >= 0 && nx < rows && ny < cols && dist[nx][ny] > dist[x][y] + 1) {

dist[nx][ny] = dist[x][y] + 1;

q.push({nx, ny});

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return dist;

};

// Driver Codeint main() {

vector<vector<int>> mat = {

{0,0,0},

{0,1,0},

{1,1,1}

};

Solution sol;

vector<vector<int>> result = sol.updateMatrix(mat);

cout << "Updated Matrix with distances:\n";

for (auto row : result) {

for (int val : row)

cout << val << " ";

cout << endl;

return 0;

� Explanation (in 4 lines):

1. Push all 0s into the queue and set their distance to 0.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2. All 1s start with INT_MAX as their distance.
3. Use multi-source BFS to spread outwards from all 0s.
4. Update distance when a shorter path is found.

PROBLEM:329
Question : Surrounded Regions (dfs)

C++ Code Using DFS

cpp

#include <iostream>#include <vector>using namespace std;

class Solution {public:

void dfs(vector<vector<char>>& board, int i, int j) {

int rows = board.size(), cols = board[0].size();

if (i < 0 || j < 0 || i >= rows || j >= cols || board[i][j] != 'O')

return;

board[i][j] = '#'; // Temporarily mark border-connected 'O'

dfs(board, i+1, j);

dfs(board, i-1, j);

dfs(board, i, j+1);

dfs(board, i, j-1);

void solve(vector<vector<char>>& board) {

if (board.empty()) return;

int rows = board.size(), cols = board[0].size();

// Step 1: Run DFS on border 'O's

for (int i = 0; i < rows; ++i) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (board[i][0] == 'O') dfs(board, i, 0);

if (board[i][cols-1] == 'O') dfs(board, i, cols-1);

for (int j = 0; j < cols; ++j) {

if (board[0][j] == 'O') dfs(board, 0, j);

if (board[rows-1][j] == 'O') dfs(board, rows-1, j);

// Step 2: Flip and restore

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < cols; ++j) {

if (board[i][j] == 'O')

board[i][j] = 'X'; // Surrounded

else if (board[i][j] == '#')

board[i][j] = 'O'; // Border-connected

};

// Driver Codeint main() {

vector<vector<char>> board = {

{'X','X','X','X'},

{'X','O','O','X'},

{'X','X','O','X'},

{'X','O','X','X'}

};

Solution sol;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


sol.solve(board);

cout << "Solved Board:\n";

for (auto row : board) {

for (char c : row)

cout << c << " ";

cout << endl;

return 0;

� Explanation (in 4 lines):

1. DFS from all 'O's on the border and mark them as '#'.
2. These '#' are safe and won’t be flipped.
3. Flip remaining 'O's to 'X' since they are enclosed.
4. Restore '#' back to 'O'.

PROBLEM:330
Question : Number of Enclaves [flood fill implementation - multisource]

C++ Code (Multi-source DFS Flood Fill)

cpp

#include <iostream>#include <vector>using namespace std;

class Solution {public:

void dfs(vector<vector<int>>& grid, int i, int j) {

int rows = grid.size(), cols = grid[0].size();

if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] != 1)

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


grid[i][j] = -1; // Mark as visited (or sea)

dfs(grid, i+1, j);

dfs(grid, i-1, j);

dfs(grid, i, j+1);

dfs(grid, i, j-1);

int numEnclaves(vector<vector<int>>& grid) {

int rows = grid.size(), cols = grid[0].size();

// Step 1: Run DFS for all boundary 1s

for (int i = 0; i < rows; ++i) {

if (grid[i][0] == 1) dfs(grid, i, 0);

if (grid[i][cols-1] == 1) dfs(grid, i, cols-1);

for (int j = 0; j < cols; ++j) {

if (grid[0][j] == 1) dfs(grid, 0, j);

if (grid[rows-1][j] == 1) dfs(grid, rows-1, j);

// Step 2: Count remaining 1s

int count = 0;

for (int i = 0; i < rows; ++i)

for (int j = 0; j < cols; ++j)

if (grid[i][j] == 1)

count++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return count;

};

// Driver Codeint main() {

vector<vector<int>> grid = {

{0,0,0,0},

{1,0,1,0},

{0,1,1,0},

{0,0,0,0}

};

Solution sol;

int enclaves = sol.numEnclaves(grid);

cout << "Number of enclave land cells: " << enclaves << endl;

return 0;

� Explanation (in 4 lines):

1. Run DFS from all boundary land cells (value 1) to mark reachable ones.
2. Mark those as visited (e.g. with -1) since they can't be enclaves.
3. After flood fill, the leftover 1s are enclaves.
4. Count and return them.

PROBLEM:331
Question : Word ladder - 1

C++ Code (Using BFS)

cpp

#include <iostream>#include <vector>#include <unordered_set>#include <queue>using


namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


class Solution {public:

int ladderLength(string beginWord, string endWord, vector<string>& wordList) {

unordered_set<string> wordSet(wordList.begin(), wordList.end());

if (wordSet.find(endWord) == wordSet.end()) return 0;

queue<pair<string, int>> q;

q.push({beginWord, 1});

while (!q.empty()) {

auto [word, level] = q.front(); q.pop();

if (word == endWord) return level;

for (int i = 0; i < word.size(); i++) {

string temp = word;

for (char ch = 'a'; ch <= 'z'; ch++) {

temp[i] = ch;

if (wordSet.find(temp) != wordSet.end()) {

q.push({temp, level + 1});

wordSet.erase(temp); // prevent cycles

return 0;

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Driver Codeint main() {

string beginWord = "hit", endWord = "cog";

vector<string> wordList = {"hot","dot","dog","lot","log","cog"};

Solution sol;

int result = sol.ladderLength(beginWord, endWord, wordList);

cout << "Shortest transformation length: " << result << endl;

return 0;

� Explanation (in 4 lines):

1. Use BFS to explore all one-letter transformations level by level.


2. From each word, try all possible single-letter changes.
3. Push valid transformations (in wordList) into the queue with level+1.
4. Return the level when endWord is found, else return 0 if unreachable.

PROBLEM:332
Question : Word ladder - 2

C++ Code (BFS + Backtracking)

cpp

#include <iostream>#include <vector>#include <unordered_set>#include


<unordered_map>#include <queue>using namespace std;

class Solution {public:

vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>&


wordList) {

unordered_set<string> wordSet(wordList.begin(), wordList.end());

vector<vector<string>> result;

if (wordSet.find(endWord) == wordSet.end()) return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


unordered_map<string, vector<string>> adjList; // reverse graph

unordered_map<string, int> visited;

queue<string> q;

q.push(beginWord);

visited[beginWord] = 0;

while (!q.empty()) {

string word = q.front(); q.pop();

int currLevel = visited[word];

for (int i = 0; i < word.size(); i++) {

string temp = word;

for (char ch = 'a'; ch <= 'z'; ch++) {

temp[i] = ch;

if (wordSet.find(temp) != wordSet.end()) {

if (!visited.count(temp)) {

visited[temp] = currLevel + 1;

q.push(temp);

adjList[temp].push_back(word); // reverse link

} else if (visited[temp] == currLevel + 1) {

adjList[temp].push_back(word); // add multiple parents

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (!visited.count(endWord)) return result;

vector<string> path;

dfs(endWord, beginWord, adjList, path, result);

return result;

void dfs(string word, string& beginWord, unordered_map<string, vector<string>>& adjList,

vector<string>& path, vector<vector<string>>& result) {

path.push_back(word);

if (word == beginWord) {

vector<string> temp = path;

reverse(temp.begin(), temp.end());

result.push_back(temp);

} else {

for (string parent : adjList[word]) {

dfs(parent, beginWord, adjList, path, result);

path.pop_back();

};

// Driver Codeint main() {

string beginWord = "hit", endWord = "cog";

vector<string> wordList = {"hot","dot","dog","lot","log","cog"};

Solution sol;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<vector<string>> result = sol.findLadders(beginWord, endWord, wordList);

cout << "All shortest transformation sequences:\n";

for (auto& path : result) {

for (string& word : path)

cout << word << " ";

cout << endl;

return 0;

� Explanation (in 4 lines):

1. Perform BFS to build a reverse graph where each word points to its previous
words.
2. Track word levels (depths) to ensure shortest paths only.
3. Use DFS to backtrack from endWord to beginWord using the graph.
4. Store all reversed paths as valid answers.

PROBLEM:333
Question : Number of Distinct Islands [dfs multisource]

C++ Code (DFS + Path Signature)

cpp

#include <iostream>#include <vector>#include <set>using namespace std;

class Solution {public:

void dfs(int i, int j, int baseX, int baseY, vector<vector<int>>& grid, vector<pair<int, int>>&
shape) {

int rows = grid.size(), cols = grid[0].size();

if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] != 1)

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


grid[i][j] = -1; // mark visited

shape.push_back({i - baseX, j - baseY}); // relative position

dfs(i+1, j, baseX, baseY, grid, shape);

dfs(i-1, j, baseX, baseY, grid, shape);

dfs(i, j+1, baseX, baseY, grid, shape);

dfs(i, j-1, baseX, baseY, grid, shape);

int numDistinctIslands(vector<vector<int>>& grid) {

int rows = grid.size(), cols = grid[0].size();

set<vector<pair<int, int>>> shapes;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

if (grid[i][j] == 1) {

vector<pair<int, int>> shape;

dfs(i, j, i, j, grid, shape);

shapes.insert(shape); // insert unique shape

return shapes.size();

};

// Driver Codeint main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<vector<int>> grid = {

{1,1,0,0,0},

{1,0,0,0,0},

{0,0,0,1,1},

{0,0,0,1,1}

};

Solution sol;

int count = sol.numDistinctIslands(grid);

cout << "Number of distinct islands: " << count << endl;

return 0;

� Explanation (in 4 lines):

1. Use DFS from each land cell to record island shape using relative coordinates.
2. Store each shape in a set (which keeps only unique entries).
3. Convert each island's coordinates to a shape signature.
4. Final answer = size of the set = number of distinct islands.

PROBLEM:334
Question : Bipartite Graph (DFS)

C++ Code Using DFS

cpp

#include <iostream>#include <vector>using namespace std;

class Solution {public:

bool dfs(int node, int colorVal, vector<vector<int>>& graph, vector<int>& color) {

color[node] = colorVal;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int neighbor : graph[node]) {

if (color[neighbor] == -1) {

// If not colored, color with opposite and DFS

if (!dfs(neighbor, 1 - colorVal, graph, color))

return false;

} else if (color[neighbor] == colorVal) {

// Adjacent same color → not bipartite

return false;

return true;

bool isBipartite(vector<vector<int>>& graph) {

int n = graph.size();

vector<int> color(n, -1); // -1 = unvisited

for (int i = 0; i < n; i++) {

if (color[i] == -1) {

if (!dfs(i, 0, graph, color))

return false;

return true;

};

// Driver Codeint main() {

vector<vector<int>> graph = {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


{1, 3},

{0, 2},

{1, 3},

{0, 2}

};

Solution sol;

bool result = sol.isBipartite(graph);

cout << "Is graph bipartite? " << (result ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. Color each unvisited node using DFS and alternate colors (0 or 1).
2. If any adjacent node has the same color, it's not bipartite.
3. Try DFS from every unvisited node (for disconnected graphs).
4. If no conflicts, the graph is bipartite ✅.

PROBLEM:335
Question : Cycle Detection in Directed Graph (DFS)

✅ C++ Code (DFS with Recursion Stack)

cpp

#include <iostream>#include <vector>using namespace std;

class Solution {public:

bool dfs(int node, vector<vector<int>>& graph, vector<bool>& visited, vector<bool>&


recStack) {

visited[node] = true;

recStack[node] = true; // mark current path

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int neighbor : graph[node]) {

if (!visited[neighbor]) {

if (dfs(neighbor, graph, visited, recStack))

return true;

else if (recStack[neighbor]) {

// If node is in current path → cycle

return true;

recStack[node] = false; // remove from path

return false;

bool hasCycle(int V, vector<vector<int>>& graph) {

vector<bool> visited(V, false), recStack(V, false);

for (int i = 0; i < V; i++) {

if (!visited[i])

if (dfs(i, graph, visited, recStack))

return true;

return false;

};

// Driver Codeint main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int V = 4;

vector<vector<int>> graph = {

{1}, // 0 → 1

{2}, // 1 → 2

{3}, // 2 → 3

{1} // 3 → 1 (cycle here)

};

Solution sol;

bool hasCycle = sol.hasCycle(V, graph);

cout << "Cycle in Directed Graph? " << (hasCycle ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. Use DFS from every unvisited node and track the current recursion path using
recStack.
2. If during DFS, you revisit a node already in the recursion path → cycle detected.
3. Remove node from recStack once DFS call ends.
4. If any DFS detects a cycle, return true; otherwise, it's acyclic ✅.

PROBLEM:336
Question : Topo Sort

✅ C++ Code (DFS-Based Topological Sort)

cpp

#include <iostream>#include <vector>#include <stack>using namespace std;

class Solution {public:

void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited, stack<int>& st) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


visited[node] = true;

for (int neighbor : graph[node]) {

if (!visited[neighbor])

dfs(neighbor, graph, visited, st);

st.push(node); // all children done → push to stack

vector<int> topoSort(int V, vector<vector<int>>& graph) {

vector<bool> visited(V, false);

stack<int> st;

vector<int> result;

for (int i = 0; i < V; i++) {

if (!visited[i])

dfs(i, graph, visited, st);

while (!st.empty()) {

result.push_back(st.top());

st.pop();

return result;

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Driver Codeint main() {

int V = 6;

vector<vector<int>> graph(V);

graph[5].push_back(0);

graph[5].push_back(2);

graph[4].push_back(0);

graph[4].push_back(1);

graph[2].push_back(3);

graph[3].push_back(1);

Solution sol;

vector<int> order = sol.topoSort(V, graph);

cout << "Topological Sort Order: ";

for (int node : order)

cout << node << " ";

cout << endl;

return 0;

� Explanation (in 4 lines):

1. Use DFS to visit all descendants of a node before adding it to the result.
2. After visiting all neighbors, push node onto stack (post-order).
3. Repeat for all unvisited nodes to handle disconnected graphs.
4. Pop from stack to get the topological order.

PROBLEM:337
Question : Kahn's Algorithm

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ C++ Code – Kahn's Algorithm

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class Solution {public:

vector<int> kahnTopoSort(int V, vector<vector<int>>& graph) {

vector<int> indegree(V, 0);

for (int u = 0; u < V; u++) {

for (int v : graph[u])

indegree[v]++;

queue<int> q;

for (int i = 0; i < V; i++) {

if (indegree[i] == 0)

q.push(i); // start with nodes having no prerequisites

vector<int> topo;

while (!q.empty()) {

int node = q.front(); q.pop();

topo.push_back(node);

for (int neighbor : graph[node]) {

indegree[neighbor]--;

if (indegree[neighbor] == 0)

q.push(neighbor);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Check for cycle (if topo sort couldn't include all nodes)

if (topo.size() != V)

return {}; // cycle detected → no valid topo sort

return topo;

};

// Driver Codeint main() {

int V = 6;

vector<vector<int>> graph(V);

graph[5] = {0, 2};

graph[4] = {0, 1};

graph[2] = {3};

graph[3] = {1};

Solution sol;

vector<int> order = sol.kahnTopoSort(V, graph);

if (order.empty()) {

cout << "Cycle detected! No Topological Sort exists.\n";

} else {

cout << "Topological Sort (Kahn's Algorithm): ";

for (int node : order)

cout << node << " ";

cout << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return 0;

� Explanation (in 4 lines):

1. Compute the indegree of all nodes (number of incoming edges).


2. Start BFS from nodes with 0 indegree.
3. Reduce indegree of neighbors as you "process" nodes.
4. If all nodes are processed, return the result; otherwise, there's a cycle.

PROBLEM:338
Question : Cycle Detection in Directed Graph (BFS)

� Problem Summary:

Given a directed graph, detect if there’s a cycle.


We use Kahn’s Algorithm (Topological Sort) to detect cycles in a DAG.

� Intuition:

1. In a DAG, a valid topological ordering exists and includes all nodes.


2. If a cycle exists, some nodes will always have non-zero indegree (they depend
on themselves indirectly).

So, if the number of nodes in the topo sort is less than total nodes, a cycle is
present.

✅ C++ Code (Cycle Detection via Kahn's Algorithm)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class Solution {public:

bool hasCycle(int V, vector<vector<int>>& graph) {

vector<int> indegree(V, 0);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Step 1: Calculate indegree of each node

for (int u = 0; u < V; u++) {

for (int v : graph[u]) {

indegree[v]++;

// Step 2: Push all nodes with indegree 0 into queue

queue<int> q;

for (int i = 0; i < V; i++) {

if (indegree[i] == 0)

q.push(i);

int count = 0; // Count of nodes added to topological order

// Step 3: Process the graph

while (!q.empty()) {

int node = q.front();

q.pop();

count++;

for (int neighbor : graph[node]) {

indegree[neighbor]--;

if (indegree[neighbor] == 0)

q.push(neighbor);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Step 4: If not all nodes are processed, cycle exists

return count != V;

};

// Driver Codeint main() {

int V = 4;

vector<vector<int>> graph(V);

graph[0] = {1};

graph[1] = {2};

graph[2] = {3};

graph[3] = {1}; // Back edge creates a cycle

Solution sol;

cout << "Cycle in Directed Graph (BFS)? "

<< (sol.hasCycle(V, graph) ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. Count indegree for every node.


2. Process nodes with indegree 0 (using BFS).
3. For every node processed, decrement neighbors’ indegree.
4. If all nodes are not processed → cycle exists.

PROBLEM:339
Question : Course Schedule - I

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Problem Summary:

You're given numCourses and a list of prerequisite pairs [a, b] meaning to take
course a, you must first take course b.
� Can you finish all the courses?

✔️ Return true if no cycles exist (you can finish all), else false.

� Example:

Input:

numCourses = 4

prerequisites = [[1,0], [2,1], [3,2]]

Output: true
(No cycle → can finish in order: 0 → 1 → 2 → 3)

✅ C++ Code Using BFS (Kahn’s Algorithm)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class Solution {public:

bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {

vector<vector<int>> graph(numCourses);

vector<int> indegree(numCourses, 0);

for (auto& pre : prerequisites) {

int course = pre[0], prereq = pre[1];

graph[prereq].push_back(course);

indegree[course]++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


queue<int> q;

for (int i = 0; i < numCourses; i++) {

if (indegree[i] == 0)

q.push(i);

int count = 0;

while (!q.empty()) {

int curr = q.front(); q.pop();

count++;

for (int neighbor : graph[curr]) {

indegree[neighbor]--;

if (indegree[neighbor] == 0)

q.push(neighbor);

return count == numCourses;

};

// Driver Codeint main() {

int numCourses = 4;

vector<vector<int>> prerequisites = {{1,0}, {2,1}, {3,2}};

Solution sol;

cout << (sol.canFinish(numCourses, prerequisites) ? "Yes, can finish all courses." : "No,
cycle detected!") << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Explanation (in 4 lines):

1. Build graph and calculate indegree of each course.


2. Use Kahn’s algorithm (BFS) to simulate taking courses with 0 prereqs.
3. Count how many courses you can take in order.
4. If count equals total courses → no cycle, else cycle detected.

PROBLEM:340
Question : Course Schedule - II

C++ Code (Kahn's Algorithm – BFS Topological Sort)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class Solution {public:

vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {

vector<vector<int>> graph(numCourses);

vector<int> indegree(numCourses, 0);

for (auto& pre : prerequisites) {

int course = pre[0], prereq = pre[1];

graph[prereq].push_back(course);

indegree[course]++;

queue<int> q;

for (int i = 0; i < numCourses; ++i) {

if (indegree[i] == 0)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


q.push(i);

vector<int> order;

while (!q.empty()) {

int curr = q.front(); q.pop();

order.push_back(curr);

for (int neighbor : graph[curr]) {

indegree[neighbor]--;

if (indegree[neighbor] == 0)

q.push(neighbor);

// Check if all courses are included

if (order.size() != numCourses)

return {}; // Cycle detected, no valid order

return order;

};

// Driver Codeint main() {

int numCourses = 4;

vector<vector<int>> prerequisites = {{1,0},{2,0},{3,1},{3,2}};

Solution sol;

vector<int> result = sol.findOrder(numCourses, prerequisites);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (result.empty()) {

cout << "No valid course order exists (cycle detected)." << endl;

} else {

cout << "Course order: ";

for (int course : result)

cout << course << " ";

cout << endl;

return 0;

� Explanation (in 4 lines):

1. Build a graph and compute indegrees of all courses.


2. Add all 0-indegree courses to queue and perform BFS.
3. Each time you take a course, reduce the indegree of its neighbors.
4. If you can finish all courses, return the order, else return [].

PROBLEM:341
Question : Find eventual safe states

✅ C++ Code (DFS + Coloring)

cpp

#include <iostream>#include <vector>using namespace std;

class Solution {public:

bool dfs(int node, vector<vector<int>>& graph, vector<int>& state) {

if (state[node] != 0) return state[node] == 2;

state[node] = 1; // Mark as visiting

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int neighbor : graph[node]) {

if (!dfs(neighbor, graph, state)) {

return false;

state[node] = 2; // Mark as safe

return true;

vector<int> eventualSafeNodes(vector<vector<int>>& graph) {

int n = graph.size();

vector<int> state(n, 0); // 0 = unvisited, 1 = visiting, 2 = safe

vector<int> result;

for (int i = 0; i < n; ++i) {

if (dfs(i, graph, state))

result.push_back(i);

return result;

};

// Driver Codeint main() {

vector<vector<int>> graph = {

{1,2}, {2,3}, {5}, {0}, {5}, {}, {}

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Solution sol;

vector<int> safeNodes = sol.eventualSafeNodes(graph);

cout << "Safe nodes: ";

for (int node : safeNodes)

cout << node << " ";

cout << endl;

return 0;

� Explanation (in 4 lines):

1. Use DFS with a coloring method:


0 = unvisited, 1 = visiting, 2 = safe.
2. If during DFS we revisit a 1, there’s a cycle → unsafe.
3. Nodes that finish DFS with no cycles are marked as 2 (safe).
4. Collect all safe nodes in ascending order.

PROBLEM:342
Question : Alien dictionary

✅ C++ Code (Topological Sort via Kahn’s Algorithm)

cpp

#include <iostream>#include <vector>#include <unordered_map>#include <queue>#include


<string>#include <set>using namespace std;

class Solution {public:

string alienOrder(vector<string>& words) {

unordered_map<char, set<char>> graph;

unordered_map<char, int> indegree;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Initialize graph with all unique characters

for (string word : words) {

for (char ch : word) {

graph[ch];

indegree[ch] = 0;

// Build graph by comparing adjacent words

for (int i = 0; i < words.size() - 1; i++) {

string w1 = words[i], w2 = words[i + 1];

int len = min(w1.length(), w2.length());

bool found = false;

for (int j = 0; j < len; j++) {

if (w1[j] != w2[j]) {

if (!graph[w1[j]].count(w2[j])) {

graph[w1[j]].insert(w2[j]);

indegree[w2[j]]++;

found = true;

break;

// Invalid case: prefix comes after (e.g., "abc", "ab")

if (!found && w1.length() > w2.length())

return "";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Topological sort using Kahn’s algorithm

queue<char> q;

for (auto& [ch, deg] : indegree) {

if (deg == 0) q.push(ch);

string result = "";

while (!q.empty()) {

char curr = q.front(); q.pop();

result += curr;

for (char neighbor : graph[curr]) {

indegree[neighbor]--;

if (indegree[neighbor] == 0)

q.push(neighbor);

return result.length() == indegree.size() ? result : "";

};

// Driver Codeint main() {

vector<string> words = {"wrt", "wrf", "er", "ett", "rftt"};

Solution sol;

string order = sol.alienOrder(words);

if (order == "")

cout << "Invalid alien dictionary (cycle detected)." << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else

cout << "Alien Dictionary Order: " << order << endl;

return 0;

� Explanation (in 4 lines):

1. Compare adjacent words to build character precedence (a → b).


2. Create a graph + indegree map from the ordering.
3. Use Kahn's Algorithm to perform topological sort.
4. If result size matches unique chars, return it; else, return "" (cycle).

PROBLEM:343
Question : Shortest Path in UG with unit weights

C++ program

cpp

#include <iostream>

#include <vector>

#include <queue>

using namespace std;

// Function to perform BFS and find shortest paths from source

void shortestPath(int V, vector<int> adj[], int src) {

vector<int> dist(V, -1); // Distance from source to each node (-1 means unreachable)

queue<int> q;

dist[src] = 0;

q.push(src);

while (!q.empty()) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int node = q.front();

q.pop();

for (int neighbor : adj[node]) {

if (dist[neighbor] == -1) {

dist[neighbor] = dist[node] + 1;

q.push(neighbor);

// Print the shortest distances

cout << "Shortest distances from node " << src << ":\n";

for (int i = 0; i < V; ++i) {

cout << "To node " << i << ": " << dist[i] << '\n';

int main() {

int V = 6; // Number of vertices

vector<int> adj[V];

// Add undirected edges (example graph)

adj[0].push_back(1);

adj[1].push_back(0);

adj[0].push_back(2);

adj[2].push_back(0);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


adj[1].push_back(3);

adj[3].push_back(1);

adj[2].push_back(3);

adj[3].push_back(2);

adj[3].push_back(4);

adj[4].push_back(3);

adj[4].push_back(5);

adj[5].push_back(4);

int source = 0;

shortestPath(V, adj, source);

return 0;

� Explanation (in 4 lines):

1. The graph is stored as an adjacency list, and all edges have unit weight.
2. A BFS is performed from the source node to compute the shortest distance to all
other nodes.
3. A dist array keeps track of the shortest distance from the source to each node.
4. The final distances are printed after BFS traversal is complete.

PROBLEM:344

Question : Shortest Path in DAG

C++

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <iostream>

#include <vector>

#include <stack>

#include <limits>

using namespace std;

const int INF = numeric_limits<int>::max();

void topoSort(int node, vector<pair<int, int>> adj[], vector<bool> &visited, stack<int> &st) {

visited[node] = true;

for (auto [neighbor, weight] : adj[node]) {

if (!visited[neighbor])

topoSort(neighbor, adj, visited, st);

st.push(node);

void shortestPathDAG(int V, vector<pair<int, int>> adj[], int src) {

vector<bool> visited(V, false);

stack<int> st;

// Topological sort

for (int i = 0; i < V; ++i)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (!visited[i])

topoSort(i, adj, visited, st);

// Initialize distances

vector<int> dist(V, INF);

dist[src] = 0;

// Relax nodes in topological order

while (!st.empty()) {

int u = st.top(); st.pop();

if (dist[u] != INF) {

for (auto [v, weight] : adj[u]) {

if (dist[u] + weight < dist[v])

dist[v] = dist[u] + weight;

// Output distances

cout << "Shortest distances from node " << src << ":\n";

for (int i = 0; i < V; ++i) {

if (dist[i] == INF)

cout << "To node " << i << ": INF\n";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else

cout << "To node " << i << ": " << dist[i] << '\n';

int main() {

int V = 6;

vector<pair<int, int>> adj[V];

// Add directed edges: (from, to, weight)

adj[0].push_back({1, 2});

adj[0].push_back({4, 1});

adj[1].push_back({2, 3});

adj[2].push_back({3, 6});

adj[4].push_back({2, 2});

adj[4].push_back({5, 4});

adj[5].push_back({3, 1});

int source = 0;

shortestPathDAG(V, adj, source);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� 4-Line Explanation:

1. The graph is represented as an adjacency list with weights.


2. A topological sort is performed to order nodes respecting dependencies.
3. Nodes are relaxed in topological order to find the shortest distances from the
source.
4. Final shortest distances are printed; unreachable nodes show as "INF"

PROBLEM:345

Question : Djisktra's Algorithm

C++

Cpp

#include <iostream>

#include <vector>

#include <queue>

#include <limits>

using namespace std;

const int INF = numeric_limits<int>::max();

void dijkstra(int V, vector<pair<int, int>> adj[], int src) {

vector<int> dist(V, INF);

dist[src] = 0;

// Min-heap priority queue: (distance, node)

priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;

pq.push({0, src});

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (!pq.empty()) {

int d = pq.top().first;

int u = pq.top().second;

pq.pop();

if (d > dist[u]) continue;

for (auto [v, w] : adj[u]) {

if (dist[u] + w < dist[v]) {

dist[v] = dist[u] + w;

pq.push({dist[v], v});

// Print distances

cout << "Shortest distances from node " << src << ":\n";

for (int i = 0; i < V; ++i) {

if (dist[i] == INF)

cout << "To node " << i << ": INF\n";

else

cout << "To node " << i << ": " << dist[i] << '\n';

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

int V = 5;

vector<pair<int, int>> adj[V];

// Add directed edges: (from, to, weight)

adj[0].push_back({1, 10});

adj[0].push_back({4, 5});

adj[1].push_back({2, 1});

adj[1].push_back({4, 2});

adj[2].push_back({3, 4});

adj[3].push_back({0, 7});

adj[4].push_back({1, 3});

adj[4].push_back({2, 9});

adj[4].push_back({3, 2});

int source = 0;

dijkstra(V, adj, source);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� 4-Line Explanation:

1. A min-priority queue is used to always expand the closest unvisited node.


2. The dist[] array keeps track of the shortest distances from the source.
3. Each edge is relaxed if a shorter path to the neighbor is found.
4. Final distances from the source to all nodes are printed.

Congratulations on completing the PDF created by SYNTAX ERROR, also known as


Abhishek Rathor!
Your dedication and perseverance are truly commendable. For more insights and
updates, feel free
to connect on Instagram at SYNTAX ERROR.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

You might also like