Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the Node structure for a binary tree.
DSA C++
struct Node {
int data;
Node* [1];
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
}; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'next' instead of 'left' for the left child pointer.
✗ Incorrect
The left child pointer in a binary tree node is commonly named 'left'.
2fill in blank
mediumComplete the code to check if a node is a leaf node.
DSA C++
bool isLeaf(Node* node) {
return node != nullptr && node->left == nullptr && node->[1] == nullptr;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking wrong pointer names like 'parent' or 'next'.
✗ Incorrect
A leaf node has no left or right children, so both pointers should be nullptr.
3fill in blank
hardFix the error in the function to add left boundary nodes (excluding leaves).
DSA C++
void addLeftBoundary(Node* root, vector<int>& res) {
Node* cur = root->left;
while (cur != nullptr) {
if (!isLeaf(cur)) res.push_back(cur->[1]);
if (cur->left != nullptr) cur = cur->left;
else cur = cur->right;
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'left' or 'right' instead of 'data' to get the node's value.
✗ Incorrect
To add the node's value, we access the 'data' member, not the child pointers.
4fill in blank
hardFill both blanks to add right boundary nodes in reverse order (excluding leaves).
DSA C++
void addRightBoundary(Node* root, vector<int>& res) {
Node* cur = root->[1];
vector<int> tmp;
while (cur != nullptr) {
if (!isLeaf(cur)) tmp.push_back(cur->[2]);
if (cur->right != nullptr) cur = cur->right;
else cur = cur->left;
}
for (int i = tmp.size() - 1; i >= 0; --i) res.push_back(tmp[i]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from left child or adding pointers instead of values.
✗ Incorrect
Start from the right child of root and add node values (data) to tmp vector.
5fill in blank
hardFill in the blank to complete the boundary traversal function.
DSA C++
vector<int> boundaryTraversal(Node* root) {
vector<int> res;
if (root == nullptr) return res;
if (!isLeaf(root)) res.push_back(root->[1]);
addLeftBoundary(root, res);
addLeaves(root, res);
addRightBoundary(root, res);
return res;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding root pointer or child pointers instead of root's value.
✗ Incorrect
The root's value is stored in 'data' and should be added if root is not a leaf.