My coding exercise is given the reference to the node count its children. I decided to use recursion, and I was wondering is this a elegant way to do this:
Let's assume there is class Node which represents every node in the tree:
public Node {
int data:
Node left;
Node right;
}
int countChildren(Node head) {
if(head==null) return 0;
return countChildren(head.left)+countChildren(head.right)+
((head.left==null)?0:1) + ((head.right==null)?0:1);
}
This is my suggestion.