I am supposed to implement a recursive method that counts the amount of left-child tree nodes. My code so far is:
private int countLeftNodes(IntTreeNode node){
int c = 0;
if (node != null){
c = 1 + countLeftNodes(node.left);
countLeftNodes(node.right);
}
return c;
}
It returns a number much smaller than what it should be. I have a feeling that my traversal is off because it seems to only count the very left child nodes, and then terminates. When I call this method on an IntTree of size 16 I should get 8 left-child nodes, 7 right-child nodes, and one root, but instead I get 4 left-child nodes.
You never count the left nodes in the right tree.
private int countLeftNodes(IntTreeNode node)
{
int c = 0;
if (node.left != null)
{
c += 1 + countLeftNodes(node.left);
}
if(node.right != null)
{
c += countLeftNodes(node.right);
}
return c;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With