美文网首页Python
python-026-找出与输入值相等的二叉树路径。

python-026-找出与输入值相等的二叉树路径。

作者: DKider | 来源:发表于2019-04-07 21:23 被阅读9次

    给定一个二叉树,并输入一个数,找出二叉树中从根节点到叶子节点的路径和与输入值相等的路径。

    这篇放了很久了,是以前写的,今天没有新的产出,写了一下午的C。
    真是难为我了。

    import random
    class BiTNode:
        def __init__(self, arg):
            self.data = arg
            self.left_child = None
            self.right_child = None
    # 构造二叉树
    def constructBitree(x):
        # x为二叉树节点个数
        arr=[]
        for i in range(x):
            arr.append(random.randint(-9, 9))
        root=arrayToBiTree(arr)
        return root
    def arrayToBiTree(array):
        #判断arr是否为空
        if len(array)==0:
            return BiTNode(array[0])
        mid=len(array)//2 # 有序数组的中间元素的下标
        # print(mid)
        # start=0 # 数组第一个元素的下标
        # end=-1 # 数组最后一个元素的下标
        root = None
        if len(array) > 0:
            # 将中间元素作为二叉树的根
            root=BiTNode(array[mid])
            # 如果左边的元素个数不为零,则递归调用函数,生成左子树
            if len(array[:mid]) > 0:
                root.left_child = arrayToBiTree(array[:mid])
            # 如果右边的元素个数不为零,则递归调用函数,生成左子树
            if len(array[mid+1:]) > 0:
                root.right_child = arrayToBiTree(array[mid+1:])
        return root
    
    # 从此之后函数命名都应该用下划线分割单词
    def find_path(root, number, path, sum_path):
        if root is None:
            return None
        # 前序遍历,保存从根节点到叶子节点的路径,并记录值
        sum_path = sum_path + root.data
        path.append(root.data) # 将根节点加入列表
        # 如果当前节点为叶子节点,且路径和与输入值相等,输出并继续遍历
        if (root.left_child is None and root.right_child is None) and sum_path == number:
            print("存在路径!")
            print(path)
    
        # else:
        #   print("不存在路径!")
        # 遍历左子树
        if root.left_child is not None:
            find_path(root.left_child, number, path, sum_path)
        # 遍历右子树
        if root.right_child is not None:
            find_path(root.right_child, number, path, sum_path)
        path.pop()
        sum_path = sum_path - root.data
    if __name__ == '__main__':
        root1 = constructBitree(100)
        num = int(input("请输入一个值:\n"))
        sum_path = 0  # 记录路径和
        tree_path = []  # 用于记录路径
        find_path(root1, num, tree_path, sum_path)
    # if tree_path:
    #   print("存在路径!\n为:")
    # else:
    #   print("不存在路径!")
    

    今天有点事情,而且电脑键盘坏了。就不多shuole.

    相关文章

      网友评论

        本文标题:python-026-找出与输入值相等的二叉树路径。

        本文链接:https://www.haomeiwen.com/subject/nxreiqtx.html