This may be a simple fix – but I’m trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0:
private long sum(Node<T> thisNode) { if (thisNode.Left == null && thisNode.Right == null) return 0; if (node.Right == null) return sum(thisNode.Left); if (node.Left == null) return sum(thisNode.Right); return sum(thisNode.Left) + sum(thisNode.Right); }
Within my Node class I have Data which stores Size and Name in their given properties. I’m just trying to sum the entire size. Any suggestions or ideas?
It’s because you’re returning zero when you reach a leaf node. You should be returning the size stored in that leaf node.
In addition, if your non-leaf nodes also have a size, you’ll need to process them as well thus:
If your non-leaf nodes don’t have size, use:
A more elegant version of the first one is: