user2650946
user2650946

Reputation: 41

Finding a Node in a Tree using recursion in python

class Node:
    def __init__(self, tree, data, parent=None):

        self.data = data
        self.parent = parent
        self.children = []   
        self.tree = tree

     def find(self, x):

        if self.data is x:
            return self
        elif self.children:
            for node in self.children:
                return node.find(person)
        else:
            return None

I am really stuck, i can't seem to create a method in my Node class that finds a Node with data x and returns that Node. If no Node is found, it will return None.

Upvotes: 3

Views: 8447

Answers (2)

roman
roman

Reputation: 117380

you're searching for parent in children, while you should search for x

class Node():
    def __init__(self, tree, data, parent=None):
        self.data = data
        self.parent = parent
        self.children = []   
        self.tree = tree

    def find(self, x):
        if self.data is x: return self
        for node in self.children:
            n = node.find(x)
            if n: return n
        return None


>>> n = Node(None, 1)
>>> n.children = [Node(None, 2), Node(None, 3)]
>>> print n.find(3).data
3

Upvotes: 2

RussW
RussW

Reputation: 437

I think the immediate fix would be to change this

    for node in self.children:
        return node.find(person)

To this

    for node in self.children:
        res = node.find(person)
        if res is not None:
            return res

Upvotes: 0

Related Questions