Tony Wang - 1 year ago 61
Python Question

# cofusing about lookup node with binary tree

I could print my tree in order with

`testTree.printInorder(testTree.root)`
. I have tried to lookup some node ,and the function
`findNode`
doesn't work anymore .
`print testTree.findNode(testTree.root,20)`

whatever I put in just return
`None`
. so confusing!

``````class TreeNode:
def __init__(self, value):
self.left = None;
self.right = None;
self.data = value;

class Tree:
def __init__(self):
self.root = None
if node == None:
self.root = TreeNode(value)
else:
if value < node.data:
if node.left == None:
node.left = TreeNode(value)
else:
else:
if node.right == None:
node.right = TreeNode(value)
else:

def printInorder(self,node):
if node != None:
self.printInorder(node.left)
print node.data
self.printInorder(node.right)

def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
self.findNode(node.left,value)
elif value > node.data and node.right != None:
self.findNode(node.right,value)
else:
return None
testTree = Tree()
#testTree.printInorder(testTree.root)
print testTree.findNode(testTree.root,20)
``````

Any function without an explicit return will return None.

You have not returned the recursive calls within `findNode`. So, here.

``````if value == node.data:
return node.data
elif value < node.data and node.left != None:
return self.findNode(node.left,value)
elif value > node.data and node.right != None:
return self.findNode(node.right,value)
``````

Now, I can't help but thinking this is a bit noisy. You'll always start adding from the root, yes?

``````testTree.addNode(testTree.root, 200)
``````

You could rather do this

``````testTree.addNode(200)
``````

And to do that, you basically implement your methods on the `TreeNode` class instead. So, for the `addNode`.

You could also "return up" from the recursion, rather than "pass down" the nodes as parameters.

``````class TreeNode:
def __init__(self, value):
self.left = None
self.right = None
self.data = value

if self.data == None:  # Ideally, should never end-up here
self.data = value
else:
if value < self.data:
if self.left == None:
self.left = TreeNode(value)
else:
else:
if self.right == None:
self.right = TreeNode(value)
else:

return self # Return back up the recursion
``````

Then, in the `Tree` class, just delegate the `addNode` responsibility to the root

``````class Tree:
def __init__(self):
self.root = None