Complete the code to return 0 when the node is null.
if (root == [1]) return 0;
The base case for counting nodes is when the node is null, which means no node exists, so return 0.
Complete the code to count nodes recursively by adding left and right subtree counts.
return 1 + CountNodes(root.[1]) + CountNodes(root.[2]);
We count the current node (1) plus all nodes in the left and right subtrees. The recursive calls use root.left and root.right.
Fix the error in the recursive call to count the right subtree.
return 1 + CountNodes(root.left) + CountNodes(root.[1]);
The right subtree is accessed by the 'right' property, so the recursive call must use root.right.
Fill both blanks to create a method that counts nodes in a binary tree.
public int CountNodes([1] root) { if (root == null) return 0; return 1 + CountNodes(root.[2]) + CountNodes(root.right); }
The method parameter type is 'TreeNode'. To count left subtree nodes, use 'root.left'.
Fill all four blanks to complete the binary tree node class and counting method.
public class TreeNode { public int val; public TreeNode [1]; public TreeNode [2]; public TreeNode(int value) { val = value; [3] = null; [4] = null; } } public int CountNodes(TreeNode root) { if (root == null) return 0; return 1 + CountNodes(root.left) + CountNodes(root.right); }
The TreeNode class has 'left' and 'right' children. The constructor initializes these to null using the same names.
