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);
}
You dont need to write any base case for depth ==0 because your code is covering that thing as when your recursive function call get back to root node(depth==0) then it will not satisfy the if condition which is (if(depth % 2 != 0))and will return the value left+right+1 means you are adding the value 1 of root node itself and then returning it.
Here is my recursive code for finding the number of nodes at even depths in a...