0
0
DSA C++programming~10 mins

Boundary Traversal of Binary Tree in DSA C++ - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Aleft
Bparent
Cchild
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'next' instead of 'left' for the left child pointer.
2fill in blank
medium

Complete 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'
Aparent
Bright
Cchild
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Checking wrong pointer names like 'parent' or 'next'.
3fill in blank
hard

Fix 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'
Aright
Bleft
Cdata
Dparent
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'left' or 'right' instead of 'data' to get the node's value.
4fill in blank
hard

Fill 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'
Aright
Bleft
Cdata
Dparent
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from left child or adding pointers instead of values.
5fill in blank
hard

Fill 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'
Adata
Bleft
Cright
Dparent
Attempts:
3 left
💡 Hint
Common Mistakes
Adding root pointer or child pointers instead of root's value.