Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a tree node struct with an integer value.
DSA C++
struct TreeNode {
int val;
TreeNode* [1];
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 'next' which is common in linked lists, not trees.
✗ Incorrect
In a binary tree node, the left child pointer is commonly named 'left'.
2fill in blank
mediumComplete the code to add an edge between two nodes in an undirected graph represented by adjacency list.
DSA C++
void addEdge(vector<int> adj[], int u, int v) {
adj[u].push_back([1]);
adj[v].push_back(u);
}Attempts:
3 left
💡 Hint
Common Mistakes
Pushing u instead of v, which adds a self-loop.
✗ Incorrect
To add an edge from u to v, we push v into u's adjacency list.
3fill in blank
hardFix the error in the code that checks if a graph has a cycle using DFS.
DSA C++
bool dfs(int node, int parent, vector<int> adj[], vector<bool>& visited) {
visited[node] = true;
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
if (dfs(neighbor, node, adj, visited)) return true;
} else if (neighbor != [1]) {
return true;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing neighbor with node instead of parent.
✗ Incorrect
When checking for a cycle, we ignore the edge back to the parent node.
4fill in blank
hardFill both blanks to create a function that checks if a graph is a tree by verifying edges and connectivity.
DSA C++
bool isTree(int V, vector<int> adj[]) {
vector<bool> visited(V, false);
int edgeCount = 0;
for (int i = 0; i < V; i++) {
edgeCount += adj[i].size();
}
if (edgeCount / [1] != V - 1) return false;
dfs(0, -1, adj, visited);
for (bool v : visited) {
if (!v) return [2];
}
return true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Not dividing edge count by 2.
Returning true when nodes are unvisited.
✗ Incorrect
A tree with V nodes has exactly V-1 edges, so edgeCount must be divided by 2 (undirected edges counted twice). Also, if any node is not visited, the graph is not connected, so return false.
5fill in blank
hardFill all three blanks to implement BFS traversal of a graph starting from node 0.
DSA C++
void bfs(int start, vector<int> adj[], vector<bool>& visited) {
queue<int> q;
q.push(start);
visited[start] = [1];
while (!q.empty()) {
int node = q.front();
q.pop();
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
visited[neighbor] = [2];
q.[3](neighbor);
}
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Marking visited as false.
Using pop instead of push to add neighbors.
✗ Incorrect
We mark nodes as visited by setting visited[node] = true. We add neighbors to the queue using push.
