Java-
With Binary Tree we want to count the nodes after a certain depth.
Add a recursive method countNodesAtDepth to your Driver class, which takes two parameters: an Integer node n and an integer d. This method should return the number of nodes at depth d in the subtree rooted at n.
Hint: if a node is at depth d in the subtree rooted at n, what depth is it at in the subtree rooted at n.left or n.right? What are the possible base cases for your recursive method?
/*If you have any query do comment in the comment section else like the solution*/
//Below code will return number of nodes at particular depth d, if you want to count number of nodes at depth d and after that, then just change d==0 to d<=0
int countNodesAtDepth(node n, int d) {
if(n == null) return 0;
if(n.left == null && n.right == null) {
if(d == 0) {
return 1;
}
}
if(d == 0) {
return 1 +
countNodesAtDepth(n.left, d-1) + countNodesAtDepth(n.right,
d-1);
}
return countNodesAtDepth(n.left, d-1) +
countNodesAtDepth(n.right, d-1);
}
Get Answers For Free
Most questions answered within 1 hours.