Question

Here is my recursive code for finding the number of nodes at even depths in a...

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);

}

0 0
Add a comment Improve this question Transcribed image text
Answer #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.

Add a comment
Know the answer?
Add Answer to:
Here is my recursive code for finding the number of nodes at even depths in a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT