求一棵二叉树的最大子树和

解题思路

针对每棵子树,求出这棵子树中所有节点的和,然后从中找到最大值。

在对二叉树的后序遍历中,如果当前遍历节点的值与其左右子树和的值相加大于最大值,则更新最大值。

代码实现

"""求一颗二叉树的最大子树和"""
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))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值