user172808
user172808

Reputation: 9

How do I search the leaves of a tree where each node could have more than two children?

I'm trying to search the leaves of a tree data structure for a target value. My function looks like this:

def searchLeaves(self, target): #DFS
        if len(self.children == 0): #is a leaf
            if self.data == target:
                return True
            else:
                return False
        else: 
            for x in self.children:
                return x.searchLeaves(target)

However, my problem is in the else statement. If it were a binary tree, I could do

else:
    return x.leftchild.searchLeaves(target) or x.rightchild.searchleaves(target)

In order to consolidate the combinations of falses and trues that the base case will produce. How could I apply this "or" logical operator to an undetermined amount of children?

Upvotes: 0

Views: 72

Answers (1)

user1342784
user1342784

Reputation:

Use any:

else:
    return any(x.searchLeaves(target) for x in self.children)

This is equivalent to this:

else:
    for x in self.children:
        if x.searchLeaves(target):
             return True
    return False

Upvotes: 5

Related Questions