Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the TreeNode class with left and right children.
DSA C#
public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; [1]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting left and right to 0 instead of null.
Creating new nodes inside the constructor unnecessarily.
✗ Incorrect
The constructor initializes left and right children to null because initially the node has no children.
2fill in blank
mediumComplete the code to calculate the height of a binary tree node recursively.
DSA C#
private int Height(TreeNode node) {
if (node == null) return 0;
int leftHeight = Height(node.left);
int rightHeight = Height(node.right);
return 1 + [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Adding left and right heights instead of taking max.
Using Math.Min which gives the shorter subtree.
✗ Incorrect
Height is 1 plus the maximum height of left or right subtree.
3fill in blank
hardFix the error in updating the diameter during recursion.
DSA C#
private int DiameterHelper(TreeNode node, ref int diameter) {
if (node == null) return 0;
int leftHeight = DiameterHelper(node.left, ref diameter);
int rightHeight = DiameterHelper(node.right, ref diameter);
diameter = Math.Max(diameter, [1]);
return 1 + Math.Max(leftHeight, rightHeight);
}Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 to the sum which counts nodes instead of edges.
Using max or min of heights instead of sum.
✗ Incorrect
Diameter is the longest path between two nodes, which is sum of left and right heights at current node.
4fill in blank
hardFill both blanks to complete the DiameterOfBinaryTree method using the helper.
DSA C#
public int DiameterOfBinaryTree(TreeNode root) {
int diameter = 0;
[1](root, ref [2]);
return diameter;
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling Height instead of DiameterHelper.
Passing root instead of diameter by reference.
✗ Incorrect
The helper method DiameterHelper is called with root and diameter reference to update diameter.
5fill in blank
hardFill all three blanks to complete the recursive DiameterHelper method.
DSA C#
private int DiameterHelper(TreeNode node, ref int diameter) {
if (node == null) return 0;
int leftHeight = DiameterHelper(node.[1], ref diameter);
int rightHeight = DiameterHelper(node.[2], ref diameter);
diameter = Math.Max(diameter, leftHeight [3] rightHeight);
return 1 + Math.Max(leftHeight, rightHeight);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using node.right for both left and right heights.
Using subtraction instead of addition for diameter update.
✗ Incorrect
Recursively get left and right heights, update diameter with their sum, then return height.
