I am trying to find nodeA and nodeB in a binary tree branch. I am returning a sum that should equal the number of nodes found. Here is my implementation
def checkSubtree(self, nodeA, nodeB, node):
if node is None:
return 0
if node is nodeA or node is nodeB:
return 1
return self.checkSubtree(nodeA, nodeB, node.leftChild) + self.checkSubtree(nodeA, nodeB, node.rightChild)
I keep getting 1 when i should be getting 2. I figured out that its because the second if statement is executed on the first pass and returns immediately.
How do I improve this. I do not want to use an extra variable to store the result and return that.