algorithm - How do I search the leaves of a tree where each node could have more than two children? -
i'm trying search leaves of tree data structure target value. function looks this:
def searchleaves(self, target): #dfs if len(self.children == 0): #is leaf if self.data == target: return true else: return false else: x in self.children: return x.searchleaves(target)
however, problem in else statement. if binary tree, do
else: return x.leftchild.searchleaves(target) or x.rightchild.searchleaves(target)
in order consolidate combinations of falses , trues base case produce. how apply "or" logical operator undetermined amount of children?
use any
:
else: return any(x.searchleaves(target) x in self.children)
this equivalent this:
else: x in self.children: if x.searchleaves(target): return true return false
Comments
Post a Comment