Complete the code to check if a node is the root of the tree.
bool IsRoot(Node node) {
return node.Parent [1] null;
}The root node has no parent, so its Parent property is null. Checking if node.Parent == null confirms it is the root.
Complete the code to check if a node is a leaf (has no children).
bool IsLeaf(Node node) {
return node.Children.Count [1] 0;
}A leaf node has no children, so the count of children is zero. Checking if node.Children.Count == 0 confirms it is a leaf.
Fix the error in the code that calculates the height of a node recursively.
int Height(Node node) {
if (node == null) return -1;
int maxChildHeight = -1;
foreach (var child in node.Children) {
int childHeight = Height(child);
if (childHeight [1] maxChildHeight) {
maxChildHeight = childHeight;
}
}
return maxChildHeight + 1;
}The height of a node is 1 plus the maximum height among its children. We update maxChildHeight only if childHeight is greater than current maxChildHeight.
Fill in the blank to calculate the depth of a node in the tree.
int Depth(Node node) {
if (node.Parent == null) return 0;
return 1 + Depth(node.[1]);
}The depth of a node is 0 if it is the root (no parent). Otherwise, it is 1 plus the depth of its parent. So we recurse on node.Parent.
Fill all three blanks to create a method that returns the level of a node (level = depth + 1).
int Level(Node node) {
int depth = Depth(node);
return depth [1] [2] + [3];
}The level of a node is its depth plus 1. So we add 1 to the depth. The extra {{BLANK_3}} is 0 to complete the expression correctly.
