Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Tree in Python

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.

like image 338
Bayko Avatar asked Jan 21 '13 13:01

Bayko


2 Answers

You're passing None to your function, which you defined with:

if root == None:
    pass

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:

 def PreOrder(self):
     print self.data 
     if self.left:
          print self.left.PreOrder()
     if self.right:
          print self.right.PreOrder()

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:

root = None
a = a.insert(root,4)
a.insert...

And so forth, your code should work.

like image 126
pcalcao Avatar answered Sep 22 '22 01:09

pcalcao


You have root = None and then in PreOrder your first line is if root == None: pass so it isn't going to do anything for you.

like image 21
hd1 Avatar answered Sep 18 '22 01:09

hd1