Question: Here is my recursive code for finding the number of nodes at even depths in a Binary Search Tree. Do I need a separate base
Here is my recursive code for finding the number of nodes at even depths in a Binary Search Tree. Do I need a separate base case for when depth == 0 (to account for the root node at depth 0, 0 is even number) or will the code below cover that? Thanks!
public int numEvenDepth(Node root) {
// tree created somehow here
int depth = 0;
return numEvenDepthHelper(root, depth);
}
public int numEvenDepthHelper(Node root, int depth) {
if(root == null)
return 0;
int left = numEvenDepthHelper(root.left, depth + 1);
int right = numEvenDepthHelper(root.right, depth + 1);
if(depth % 2 != 0)
return (left + right);
return (left+right+1);
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
