skip to Main Content

I am trying to find the left most leaf and right most leaf in the bigtree node , here is my code

from bigtree import nested_dict_to_tree, print_tree

path_dict = {
   "name": "a",
   "points": 100,
   "side":'H',
   "children": [
      {
         "name": "b",
         "points": 50,
         "side":'L',
         "children": [
            {"name": "d", "points": 40,"side":'L'},
            {"name": "e", "points": 20,"side":'R'},
         ],
      },
      {"name": "c", "points": 60,"side":'R' ,
      
         "children": [
            {"name": "f", "points": 40,"side":'L'},
            {"name": "g", "points": 20,"side":'R'},
         ]},
   ],
}

tree_root = nested_dict_to_tree(path_dict)

print_tree(tree_root)


for below output i need to get ‘d’ as right most node and ‘g’ as left most node

a
├── b
│   ├── d
│   └── e
└── c
    ├── f
    └── g

2

Answers


  1. You could use the iteration methods in the bigtree.utils module:

    from bigtree import utils
    
    # The left most leaf is the first node in a post-order traversal
    first = next(utils.iterators.postorder_iter(tree_root))
    
    # The right most leaf is the last node in a pre-order traversal
    last = None
    for last in utils.iterators.preorder_iter(tree_root):
        pass
    
    # Results:
    print(first)
    print(last)
    

    Note that you got left and right mixed up. The tree is like this:

              _a_
             /   
            b     c
           /    / 
          d   e f   g
    

    So "d" is the left most leaf and "g" the right most leaf. (See also the "side" keys in your initial dictionary).

    Login or Signup to reply.
  2. The leftmost node is referring to the first child of every node, starting from root node, while the rightmost node is referring to the last child of every node, starting from root node.

    The children of a node can be directly accessed as such,

    leftmost_node = tree_root.copy()
    while leftmost_node.children:
        leftmost_node = leftmost_node.children[0]
    
    rightmost_node = tree_root.copy()
    while rightmost_node.children:
        rightmost_node = rightmost_node.children[-1]
    

    This will result in

    leftmost_node
    # Node(/a/b/d, points=40, side=L)
    
    rightmost_node
    # Node(/a/c/g, points=20, side=R)
    

    Source: I’m the author of bigtree 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search