Winter Camp 5
Winter Camp 5
VERY EASY
1. Binary Tree Inorder Traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,2,6,5,7,1,3,9,8]
Explanation:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
CODE:
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
// Create left child
if (idx < nodeValues.size() && nodeValues[idx] != "null") {
currentNode->left = new Node(stoi(nodeValues[idx]));
nodesQueue.push(currentNode->left);
}
idx++;
return root;
}
int main() {
string input;
cout << "Enter the binary tree nodes in level order (use 'null' for empty nodes, space-separated): ";
getline(cin, input);
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
OUTPUT:
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to
the farthest leaf node.
Example 1:
Input: [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: [1,null,2]
Output: 2
Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100
CODE:
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
using namespace std;
return root;
}
int main() {
string input;
cout << "Enter the binary tree nodes in level order (use 'null' for empty nodes, space-separated): ";
getline(cin, input);
return 0;
}
OUTPUT:
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [1,2,4,5,6,7,3,8,9]
Explanation:
Constraints:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
The number of nodes in the tree is in the range [1, 100].
1 <= Node.val <= 1000
CODE:
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
using namespace std;
int main() {
string input;
cout << "Enter the binary tree nodes in level order (use 'null' for empty nodes, space-separated): ";
getline(cin, input);
// Split the input string into a vector
stringstream ss(input);
vector<string> nodeValues;
string value;
while (ss >> value) {
nodeValues.push_back(value);
}
Node* root = buildBinaryTree(nodeValues); // Create the binary tree
vector<int> traversalResult; // Vector to store the preorder traversal result
preorderTraversal(root, traversalResult); // Perform preorder traversal
// Output the result
cout << "Preorder traversal: ";
for (int val : traversalResult) {
cout << val << " ";
}
cout << endl;
return 0;
}
OUTPUT:
EASY
Given the root of a binary tree, invert the tree, and return its root.
Example 1:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Example 2:
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
CODE:
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
return root;
}
queue<Node*> nodeQueue;
nodeQueue.push(root);
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
cout << "[";
while (!nodeQueue.empty()) {
Node* currentNode = nodeQueue.front();
nodeQueue.pop();
if (currentNode) {
cout << currentNode->data << ",";
nodeQueue.push(currentNode->left);
nodeQueue.push(currentNode->right);
} else {
cout << "null,";
}
}
cout << "\b]"; // Remove the last comma
}
int main() {
string input;
cout << "Enter the binary tree nodes in level order (use 'null' for empty nodes, space-separated): ";
getline(cin, input);
return 0;
}
OUTPUT:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
MEDIUM
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and
inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
Constraints:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder and inorder consist of unique values.
Each value of inorder also appears in preorder.
preorder is guaranteed to be the preorder traversal of the tree.
inorder is guaranteed to be the inorder traversal of the tree.
CODE:
#include <iostream>
#include <vector>
#include <queue> // Include the queue header
#include <unordered_map>
#include <sstream>
using namespace std;
// Function to build the binary tree from preorder and inorder traversals
Node* constructTreeHelper(vector<int>& preorder, int preStart, int preEnd,
vector<int>& inorder, int inStart, int inEnd, unordered_map<int, int>& indexMap) {
if (preStart > preEnd || inStart > inEnd) {
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
return nullptr; // Base case: no elements to construct the tree
}
while (!nodeQueue.empty()) {
Node* currentNode = nodeQueue.front();
nodeQueue.pop();
if (currentNode) {
cout << currentNode->data << ",";
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
nodeQueue.push(currentNode->left);
nodeQueue.push(currentNode->right);
} else {
cout << "null,";
}
}
cout << "\b]"; // Remove the last comma
}
int main() {
int numNodes;
cout << "Enter the number of nodes: ";
cin >> numNodes;
vector<int> preorder(numNodes);
vector<int> inorder(numNodes);
return 0;
}
OUTPUT:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
2. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p
and q as descendants (where we allow a node to be a descendant of itself).
Example 1:
Example 2:
Example 3:
Input: root = [1,2], p = 1, q = 2
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 105].
-109 <= Node.val <= 109
All Node.val are unique.
p != q
p and q will exist in the tree.
CODE:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
#include <unordered_map>
return root;
}
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
// Function to find the lowest common ancestor of two nodes
Node* findLCA(Node* root, Node* p, Node* q) {
if (root == nullptr || root == p || root == q) {
return root; // Base case: if root is null or matches p or q
}
int main() {
string input;
cout << "Enter the binary tree nodes in level order (use 'null' for empty nodes, space-separated): ";
getline(cin, input);
// Split the input string into a vector
stringstream ss(input);
vector<string> elements;
string element;
while (ss >> element) {
elements.push_back(element);
}
Node* root = createTree(elements); // Create the binary tree
if (p && q) {
Node* lca = findLCA(root, p, q); // Find the LCA
cout << "The LCA of nodes " << value1 << " and " << value2 << " is: " << lca->value << endl;
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
} else {
cout << "One or both of the nodes do not exist in the tree." << endl;
}
return 0;
}
OUTPUT:
You are given the root of a binary tree containing digits from 0 to 9 only.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-
bit integer.
Example 1:
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 9
The depth of the tree will not exceed 10.
CODE:
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
return root;
}
// If it's a leaf node, add the current sum to the total sum
if (root->left == nullptr && root->right == nullptr) {
totalSum += currentSum;
} else {
// Recur for left and right children
computeRootToLeafSum(root->left, currentSum, totalSum);
computeRootToLeafSum(root->right, currentSum, totalSum);
}
}
int main() {
string input;
cout << "Enter the binary tree nodes in level order (use 'null' for empty nodes, space-separated): ";
getline(cin, input);
return 0;
}
OUTPUT:
HARD
1. Populating Next Right Pointers in Each Node
Example 1:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Example 2:
Input: root = []Output: []
Constraints:
The number of nodes in the tree is in the range [0, 6000].
-100 <= Node.val <= 100
Follow-up:
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for
this problem.
CODE:
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
return root;
}
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
while (!nodeQueue.empty()) {
int levelSize = nodeQueue.size();
TreeNode* previous = nullptr;
if (previous != nullptr) {
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
previous->next = currentNode; // Connect the previous node's next to the current node
}
previous = currentNode; // Update previous to the current node
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
cout << "[";
while (!nodeQueue.empty()) {
TreeNode* currentNode = nodeQueue.front();
nodeQueue.pop();
if (currentNode) {
cout << currentNode->data;
if (currentNode->next) {
cout << " -> " << currentNode->next->data;
} else {
cout << " -> #"; // Indicate the end of the level
}
cout << ", ";
if (currentNode->left) nodeQueue.push(currentNode->left);
if (currentNode->right) nodeQueue.push(currentNode->right);
}
}
cout << "\b\b]"; // Remove the last comma and space
}
int main() {
string input;
cout << "Enter the binary tree nodes in level order (use 'null' for empty nodes, space-separated): ";
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
getline(cin, input);
return 0;
}
OUTPUT:
VERY HARD
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting
of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n,
where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.
You are also given a string s of length n, where s[i] is the character assigned to the edge
between i and parent[i]. s[0] can be ignored.
Return the number of pairs of nodes (u, v) such that u < v and the characters assigned to edges on the path
from u to v can be rearranged to form a palindrome.
A string is a palindrome when it reads the same backwards as forwards.
Example 1:
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Example 2:
Input: parent = [-1,0,0,0,0], s = "aaaaa"
Output: 10
Explanation: Any pair of nodes (u,v) where u < v is valid.
Constraints:
n == parent.length == s.length
1 <= n <= 105
0 <= parent[i] <= n - 1 for all i >= 1
parent[0] == -1
parent represents a valid tree.
s consists of only lowercase English letters.
CODE:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
class PairCounter {
public:
int calculatePairs(vector<int>& parentArray, string& characters) {
int length = parentArray.size();
vector<vector<int>> treeStructure(length);
return pairCount;
}
private:
void depthFirstSearch(int node, int bitmask, vector<vector<int>>& tree, string& chars,
unordered_map<int, int>& bitmaskFrequency, int& pairCount) {
// Update the bitmask for the current character
bitmask ^= (1 << (chars[node] - 'a'));
// Decrement the frequency of the current bitmask after returning from DFS
bitmaskFrequency[bitmask]--;
}
};
int main() {
int nodeCount;
cout << "Enter the number of nodes: ";
cin >> nodeCount;
8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
vector<int> parentArray(nodeCount);
cout << "Enter the parent array: ";
for (int i = 0; i < nodeCount; ++i) {
cin >> parentArray[i];
}
string characters;
cout << "Enter the string s: ";
cin >> characters;
PairCounter solution;
int result = solution.calculatePairs(parentArray, characters);
cout << "The number of valid pairs is: " << result << endl;
return 0;
}
OUTPUT: