How do I return the children of recursive nodes in a python binary tree?

Advertisements

I currently have my code set up so I have a class that creates the first node of a binary search tree. Then, using a create_node method, I can add whatever node. How can I return the children of each created note?

When I run the following, I get an output of "Left child: None Right Child: None" when it should be "Left child: 3 Right Child: 7"

I’d assume it has something to do with the dictionary not being updated? If this is the case, how can I continually update it? Thank you!

totaldict = {}
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    def search(self, value):
        if value < self.data:
            if self.left == None:
                return False
            else:
                return self.left.search(value)
        elif value > self.data:
            if self.right == None:
                return False
            else:
                return self.right.search(value)
        else:
            return True

    def create_node(self, value):
        if value < self.data:
            if self.left == None:
                self.left = TreeNode(value)
                totaldict[value] = TreeNode(value)
            else:
                return self.left.create_node(value)
        elif value > self.data:
            if self.right == None:
                self.right = TreeNode(value)
                totaldict[value] = TreeNode(value)
            else:
                return self.right.create_node(value)
        else:
            print("Node already exists")

    def pos_child(self, value):
        if self.search(value):
            if value in totaldict:
                return "Left child: " + str(totaldict[value].left) + " Right Child: " + str(totaldict[value].right)
        else:
            print("Node does not exist, use create_node method")


root = TreeNode(10)
root.create_node(5)
root.create_node(15)
root.create_node(3)
root.create_node(7)

print(root.pos_child(5))

>Solution :

The problem is here:

if self.right == None:
    self.right = TreeNode(value)
    totaldict[value] = TreeNode(value) # HERE

You create new TreeNode but it’s not connected at all to root so it never gets any children. Change it to:

if self.right == None:
    self.right = TreeNode(value)
    totaldict[value] = self.right

And do the same for left subtree.

Leave a ReplyCancel reply