"求二叉树的最大子树和"(python)

本文介绍了一种算法,用于解决给定二叉树中寻找具有最大结点和的子树的问题。通过递归计算每个子树的总和,并与当前最大值比较更新,最终找到最大子树和及其根节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:给定一颗二叉树,它的结点都是正整数或负整数,如何找到一颗子树,使得它所有结点的和最大。

"""求一颗二叉树的最大子树和"""
class BiTNode:
    def __init__(self):
        self.data = None
        self.lchild = None
        self.rchild = None

class Test:
    def __init__(self):
        self.maxSum = -2**31

    def findMaxSubTree(self, root, maxRoot):
        if root == None:
            return 0
        # 求root左子树的所有结点的和
        lmax = self.findMaxSubTree(root.lchild, maxRoot)
        # 求root右子树的所有结点的和
        rmax = self.findMaxSubTree(root.rchild, maxRoot)
        sums = lmax + rmax + root.data

        # 以root为根的子树的和大于前面求出的最大值
        if sums > self.maxSum:
            self.maxSum = sums
            maxRoot.data = root.data
        # 返回以root为根节点的子树的所有结点的和
        return sums

    def constructTree(self):
        """构造二叉树"""
        root = BiTNode()
        node1 = BiTNode()
        node2 = BiTNode()
        node3 = BiTNode()
        node4 = BiTNode()
        root.data = 6
        node1.data = 3
        node2.data = -7
        node3.data = -1
        node4.data = 9
        root.lchild = node1
        root.rchild = node2
        node1.lchild = node3
        node1.rchild = node4
        node2.lchild = node2.rchild = node3.lchild = node3.rchild = node4.lchild = node4.rchild =None
        return root

if __name__ == "__main__":
    # 构造二叉树
    test = Test()
    root = test.constructTree()
    maxRoot = BiTNode()
    test.findMaxSubTree(root, maxRoot)
    print("最大子树和为:"+str(test.maxSum))
    print("对应子树的根节点为:"+str(maxRoot.data))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值