This is my code-snippet for a Binary Tree implementation in Python. This WORKS when I run the PreOrder function.
class Node:
def __init__(self,data):
self.left = None
self.right = None
self.data = data
class BinaryTree(Node):
def __init__(self):
self.root = None
def addNode(self,data):
return Node(data)
def insert(self,root,data):
if(root == None):
root = self.addNode(data)
else:
if(data <= root.data):
root.left = self.insert(root.left,data)
else:
root.right = self.insert(root.right,data)
return root
def PreOrder(self,root):
if root == None:
pass
else:
print(root.data)
self.PreOrder(root.left)
self.PreOrder(root.right)
a = BinaryTree()
root = a.addNode(2)
#root = None
a.insert(root,4)
a.insert(root,34)
a.insert(root,45)
a.insert(root,46)
a.insert(root,41)
a.insert(root,48)
a.PreOrder(root)
However changing the 2nd and the 3rd lines in main to
#root = a.addNode(2)
root = None
doesn’t print anything. I feel I am missing out on something basic here. Any clarifications will be gratefully appreciated.
You’re passing
Noneto your function, which you defined with:That is why nothing gets printed.
Also, this is just a personal view, I would actually make PreOrder accept only the self argument, and do the PreOrder from there, making it very simple to define recursively.
Basically something like:
But this is a matter of preference, your solution works just fine.
As blatant promotion, I actually wrote a post about writing a basic BinaryTree in Python recently, if you care to check it out, it can be found here:
http://intothewebs.tumblr.com/post/40256328302/embrace-the-basics-binary-tree
UPDATE:
Ok, after you comment, I understand your doubt.
The root parameter that is passed into your method isn’t really changed, because params in Python are passed by value:
How do I pass a variable by reference?
Read the accepted answer in this question, it’s awesome and should explain what I mean by that.
Of you have:
And so forth, your code should work.