Ad
Get All Nodes On A Given Level In A Binary Tree With Python
i am trying to get a list of nodes (objetcs) in a python binary tree, i am looking for a recursive function implemented in the node object, so i will call function on the root node, and it will going down on childs nodes till reachs the specific level, and then will return those nodes in a list
My current aproach, i'm not sure if this is correct or the best way to implement it:
def get_level_nodes(self, nodes, level=1):
if self.level > level:
return nodes
if self.level == level:
nodes.append(self)
return nodes
for child in self.child_id:
nodes += child.get_level_nodes(node, level)
return nodes
# Getting the list
nodes_list = root_node.get_level_nodes([], 3)
Ad
Answer
There is no real need to pass a list of nodes around. Each node can just return the appropriate level-nodes of its own subtree, and leave the combining of neighbours to the parent:
def get_level_nodes(self, level=1):
if self.level > level:
return []
if self.level == level:
return [self]
# child_id seems an odd name
return [n for c in self.children for n in c.get_level_nodes(level)]
A more space-efficient implementation that does not build intermediate lists for each subtree would be a generator function:
def get_level_nodes(self, level=1):
if self.level > level:
return
if self.level == level:
yield self
else:
for c in self.children:
for n in c.get_level_nodes(level):
yield n
# or in Python3
# yield from c.get_level_nodes(level)
nodes_list = list(root_node.get_level_nodes(3))
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad