二叉搜索树BST图节点平衡因子计算,binarytree,Python

x33g5p2x  于2021-11-18 转载在 Python  
字(0.9k)|赞(0)|评价(0)|浏览(346)

注意当节点非空,且在右子树高度减去左子树高度前,先给非空节点高度加1。对于本身高度为0的节点,意味着没有左右子树,直接返回平衡因子0。程序中直接使用了binarytree为每个节点的高度值属性height。

from binarytree import bst

def app():
    t = bst(height=4, is_perfect=False)
    print(t)

    print('-----')

    factors = []
    for n in t.levelorder:
        if n is None:
            continue
        else:
            factors.append((n, get_blance_factor(n)))
    print(factors)

# 平衡因子的计算,对于一个节点,该节点右子树高度减去左子树高度。
# 有些时候,也可以是左子树高度减去右子树高度。只要在代码系统中约定一致即可。
def get_blance_factor(node):
    factor = 0

    if node.height == 0:
        factor = 0
        return factor

    left = node.left
    right = node.right

    lh = 0
    rh = 0
    if left is not None:
        lh = node.left.height + 1

    if right is not None:
        rh = node.right.height + 1

    factor = rh - lh

    return factor

if __name__ == '__main__':
    app()

输出:

__11____________
         /                \
      __7        __________26
     /   \      /            \
    3     9    12___          27___
   / \              \              \
  2   6             _23            _30
 /                 /   \          /
0                 20    25       29

-----
[(Node(11), 0), (Node(7), -2), (Node(26), 0), (Node(3), -1), (Node(9), 0), (Node(12), 2), (Node(27), 2), (Node(2), -1), (Node(6), 0), (Node(23), 0), (Node(30), -1), (Node(0), 0), (Node(20), 0), (Node(25), 0), (Node(29), 0)]

相关文章