The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

前端 未结 9 771
渐次进展
渐次进展 2020-12-12 10:39

I\'m looking for the best way to calculate a nodes balance in an AVL-tree. I thought I had it working, but after some heavy inserting/updating I can see that it\'s not worki

9条回答
  •  不知归路
    2020-12-12 11:01

    This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.

    def getHeight(self,root, method='links'):
        c_node = root
        cur_lvl_nodes = [root]
        nxt_lvl_nodes = []
        height = {'links': -1, 'nodes': 0}[method]
    
        while(cur_lvl_nodes or nxt_lvl_nodes):
            for c_node in cur_lvl_nodes:
                for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):
                    nxt_lvl_nodes.append(n_node)
    
            cur_lvl_nodes = nxt_lvl_nodes
            nxt_lvl_nodes = []
            height += 1
    
        return height
    

提交回复
热议问题