Python实现完全二叉树

给定一个元素序列(如列表),递归的创建一颗完全二叉树

完整代码如下

#! /usr/bin/env python3


class TreeNode:
    """ Node of complete tree"""
    def __init__(self, data=0):
        self.data = data
        self.left = None
        self.right = None


def build(i, array):
    """ Create a compete tree based a given array"""
    if i < len(array):
        tree = TreeNode() 
        tree.data = array[i]
        tree.left = build(2*i + 1, array)
        tree.right = build(2*i + 2, array)
        return tree
    else:
        return None


def in_order(tree):
    """ traversal complete tree in order"""
    if tree != None:
        in_order(tree.left)
        print(tree.data, end=' ')
        in_order(tree.right)


def pre_order(tree):
    """ traversal complete tree pre order"""
    if tree != None:
        print(tree.data, end=' ')
        pre_order(tree.left)
        pre_order(tree.right)


def main():
    t = build(0, [4, 9, 1, 8, 3, 2, 10])
    in_order(t)
    print()
    pre_order(t)
    print()


if __name__ == '__main__':
    main()

程序的运行结果如下

posted @ 2023-11-27 22:28  Guanjie255  阅读(58)  评论(0编辑  收藏  举报