binarytree构建二叉树堆,python

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

binarytree用来构建二叉树堆很便利,比如:

from binarytree import tree, Node, build, get_parent

def app():
    my_tree = tree(height=3, is_perfect=False)
    print(my_tree.pprint(index=True))

    print('-')
    root = Node(1)  # index: 0, value: 1
    root.left = Node(2)  # index: 1, value: 2
    root.right = Node(3)  # index: 2, value: 3
    root.left.right = Node(value=4, left=Node(5), right=Node(6))  # index: 4, value: 4
    root.pprint(index=True)

    print('--')
    print(root)

    print('---')
    root.left.left = Node(15)
    print(root)

    print('----')
    root.right.right = root.left
    print(root)

    print('-----')
    root2 = build([1, 2, 3, 4, None, 5])
    print(root2)
    print('------')
    print(get_parent(root2, root2.left.left))

if __name__ == '__main__':
    app()

输出:

_________0-9_________________
      /                             \
   _1-7_____                ________2-8_
  /         \              /            \
3-4        _4-6        __5-12__         6-10_
          /           /        \             \
        9-0         11-3      12-11          14-2

None
-

   ______________0-1_
  /                  \
1-2_____             2-3
        \
       _4-4_
      /     \
    9-5     10-6

--

  ______1
 /       \
2__       3
   \
    4
   / \
  5   6

---

     ______1
    /       \
  _2__       3
 /    \
15     4
      / \
     5   6

----

     ______1
    /       \
  _2__       3___
 /    \          \
15     4         _2__
      / \       /    \
     5   6     15     4
                     / \
                    5   6

-----

    1__
   /   \
  2     3
 /     /
4     5

------

  2
 /
4

相关文章