Complete the code to define the root node of a tree.
struct Node* root = [1];The root node is the starting point of a tree and is usually initialized to NULL when the tree is empty.
Complete the code to check if a node is a leaf (has no children).
if (node->left == NULL && node->[1] == NULL) { // node is a leaf }
A leaf node has no left or right children, so both pointers are NULL.
Fix the error in the function that calculates the height of a tree node.
int height(struct Node* node) {
if (node == NULL) {
return [1];
}
int leftHeight = height(node->left);
int rightHeight = height(node->right);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}The height of an empty tree (NULL node) is defined as -1 to make leaf nodes have height 0.
Fill both blanks to calculate the depth of a node in a tree.
int depth(struct Node* node) {
if (node == NULL) {
return [1];
}
return depth(node->[2]) + 1;
}The depth of NULL (parent of root) is -1 so root depth = depth(NULL) + 1 = 0. Recursively find depth of parent and add 1.
Fill all three blanks to create a function that returns the level of a node in a tree.
int level(struct Node* root, struct Node* node, int currentLevel) {
if (root == NULL) {
return [1];
}
if (root == node) {
return [2];
}
int downlevel = level(root->left, node, currentLevel [3] 1);
if (downlevel != -1) {
return downlevel;
}
return level(root->right, node, currentLevel [3] 1);
}If the root is NULL, return -1 meaning node not found. If root is the node, return currentLevel. When searching children, increase currentLevel by 1 using '+'.
