Balanced binary tree python

前端 未结 1 884
萌比男神i
萌比男神i 2021-01-27 16:12
# stack_depth is initialised to 0
def find_in_tree(node, find_condition, stack_depth):
    assert (stack_depth < max_stack_depth), \'Deeper than max depth\'
    stack         


        
相关标签:
1条回答
  • 2021-01-27 16:31

    Instead of multiplying the number of nodes on each layer, you have to add them. For example, the number of nodes in the first four layers is 1+2+4+8=15, not 1*2*4*8=64.

                    #                      1
          #                   #          + 2
      #       #           #       #      + 4
    #   #   #   #       #   #   #   #    + 8 = 15
    

    In general, the number of nodes in the first n layers is 2**(n+1)-1. You can use logarithms to get the correct power and get the floor of that number. If you want fewer that that number, you would also have to subtract one from the power.

    >>> math.floor(math.log(1000000, 2))
    19
    >>> sum(2**i for i in range(1, 20))
    1048574
    

    Concerning your edit: Yes, stack_depth is incremented with each node, but you are incrementing a local variable. The increment will carry to the child nodes (passed as a parameter) but not to the siblings, i.e. all the nodes at level n will be called with stack_depth == n-1 (assuming it started as 0 on the first level). Thus, max_stack_depth should be 19 (or 20 if it starts with 1) to visit the ~1,000,000 nodes in the first 19 levels of the tree.

    0 讨论(0)
提交回复
热议问题