Complete the code to return the height of the binary tree when the node is null.
int height(Node* root) {
if (root == [1]) {
return 0;
}
// rest of the code
}When the node is null, the height is 0. In C++, NULL is commonly used to check for null pointers.
Complete the code to calculate the height of the left subtree.
int height(Node* root) {
if (root == NULL) {
return 0;
}
int leftHeight = height([1]);
// rest of the code
}To find the height of the left subtree, we recursively call height on root's left child.
Fix the error in the return statement to compute the height correctly.
int height(Node* root) {
if (root == NULL) {
return 0;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + [1](leftHeight, rightHeight);
}The height of a node is 1 plus the maximum height of its left and right subtrees.
Fill both blanks to complete the recursive height calculation with correct function and base case check.
int height(Node* root) {
if (root == [1]) {
return [2];
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + std::max(leftHeight, rightHeight);
}Use nullptr to check for null pointers and return 0 as the height of an empty tree.
Fill all three blanks to create a dictionary comprehension-like map of node values to their heights for nodes with height greater than 1.
std::map<int, int> nodeHeights; for (Node* node : nodes) { int h = height(node); if (h [1] 1) { nodeHeights[[2]] = [3]; } }
We check if height is greater than 1, then map node's value to its height.