I want to count the right nodes of a binary tree, for example the following one:
15
/
10
\
14
so I made the following program:
public class NodeT {
int elem;
NodeT left;
NodeT right;
public NodeT(int elem){
this.elem=elem;
left=null;
right=null;
}
}
public class Tree {
public NodeT createTree(){
NodeT root=new NodeT(15);
NodeT n1=new NodeT(10);
NodeT n4=new NodeT(14);
root.left=n1;
n1.right=n4;
return root;
}
public int countRight(NodeT root){
if (root==null) return 0; //version 1
else{
return 1+countRight(root.right);
}
}
I called my main program in the following way:
Tree tree=new Tree();
NodeT root=tree.createTree();
System.out.println(tree.countRight(root))
This code prints 1 as the correct answer, but I cannot understand why is this happening. For what I see the right branch of 15 is equal to null so the call to the recursive function countRight() should return 0 and print an incorrect answer.
I have seen other solutions and I found that for counting all the nodes they use solutions like the following:
static int n;
public int countRight(NodeT root){ //version 2
if (root==null) return 0;
if (root.left!=null){
n=countRight(root.left);
}
if (root.right!=null){
n++;
n=countRight(root.right);
}
return n;
}
which seems more legit to me. Could it be a case in which the first version fails?
Thanks