Lint 596. Minimum Subtree

Description

Solution

1.直接分值递归搜索(代码可化简)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the root of binary tree
    @return: the root of the minimum subtree
    """
    def dfs(self,root):
        if root.left is None and root.right is None:
            if self.minimum > root.val:
                self.minimum = root.val
                self.sub = root
        
            return root.val
        sum =0
        if root.left is not None:
            left = self.dfs(root.left)
            sum += left
        if root.right is not None:
            right = self.dfs(root.right)
            sum += right
        sum +=root.val
        if self.minimum > sum:
            self.minimum = sum
            self.sub = root
        return sum
    
    def findSubtree(self, root):
        self.minimum = 1e6
        self.sub = root
        self.dfs(root)
        return self.sub
        # write your code here
       

化简以后的代码(较为简单)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the root of binary tree
    @return: the root of the minimum subtree
    """
    def dfs(self,root):
        if root is None:
            return 0

        sum =0
        left = self.dfs(root.left)
        sum += left
        right = self.dfs(root.right)
        sum += right
        sum +=root.val
        if self.minimum > sum:
            self.minimum = sum
            self.sub = root
        return sum
    
    def findSubtree(self, root):
        self.minimum = 1e6
        self.sub = root
        self.dfs(root)
        return self.sub
        # write your code here
       

2.不使用额外的全局变量(在返回值做文章)
code from https://www.jiuzhang.com/solutions/minimum-subtree/#tag-highlight-lang-python

class Solution:

    def findSubtree(self, root):
        minimum, subtree, sum = self.helper(root)
        return subtree

    def helper(self, root):
        if root is None:
            return sys.maxsize, None, 0

        left_minimum, left_subtree, left_sum = self.helper(root.left)
        right_minimum, right_subtree, right_sum = self.helper(root.right)
        
        sum = left_sum + right_sum + root.val
        if left_minimum == min(left_minimum, right_minimum, sum):
            return left_minimum, left_subtree, sum
        if right_minimum == min(left_minimum, right_minimum, sum):
            return right_minimum, right_subtree, sum
        
        return sum, root, sum

你可能感兴趣的:(Lint 596. Minimum Subtree)