Complete the code to define the root node of a tree.
struct Node {
int data;
Node* left;
Node* right;
};
Node* [1] = nullptr; // Root node pointerThe root node is the topmost node of a tree. We usually name its pointer root.
Complete the code to check if a node is a leaf (no children).
bool isLeaf(Node* node) {
return node->left == nullptr && node->[1] == nullptr;
}A leaf node has no children, so both left and right pointers are nullptr.
Fix the error in the function that calculates the height of a tree node.
int height(Node* node) {
if (node == nullptr) return 0;
int leftHeight = height(node->left);
int rightHeight = height(node->[1]);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}To calculate height, we need to check both left and right children. The right child pointer is right.
Fill both blanks to create a function that returns the level (depth) of a node in the tree.
int getLevel(Node* root, Node* node, int level) {
if (root == nullptr) return 0;
if (root == node) return [1];
int downLevel = getLevel(root->left, node, level [2] 1);
if (downLevel != 0) return downLevel;
return getLevel(root->right, node, level [2] 1);
}The current level is passed as level. When the node is found, return level. When going deeper, increase level by 1 using level + 1.
Fill all three blanks to create a function that prints nodes at a given level.
void printLevelNodes(Node* root, int level) {
if (root == nullptr) return;
if (level == [1]) {
std::cout << root->data << " ";
} else if (level > [2]) {
printLevelNodes(root->left, level [3] 1);
printLevelNodes(root->right, level [3] 1);
}
}Nodes at level 0 are the root nodes. We check if level == 0. If level is greater than 0, we go down by subtracting 1 from level.