zoukankan      html  css  js  c++  java
  • Day4 -- Most Frequent Subtree Sum

    Most Frequent Subtree Sum



    Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

    Examples 1
    Input:

    5
    /
    2 -3
    return [2, -3, 4], since all the values happen only once, return all of them in any order.
    Examples 2
    Input:

    5
    /
    2 -5
    return [2], since 2 happens twice, however -5 only occur once.
    Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

    solution

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Time    : 2018/11/22 
    
    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    
    class Solution:
    
        def findFrequentTreeSum(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            map1 = {}
    
            def helper(root):
                if not root: return 0
                left_val = helper(root.left)
                right_val = helper(root.right)
                cur_sum = left_val + right_val + root.val
                print "cur_sum", cur_sum, left_val, right_val, root.val
                map1[cur_sum] = 1 if not map1.get(cur_sum) else map1[cur_sum] + 1
                return cur_sum
    
            helper(root)
            print "map", map1
            res = []
            value_list = [v for v in sorted(map1.values())]
            if value_list:
                max_fre = value_list[-1]
                res = [k for k, v in map1.items() if v == max_fre]
            return res
    
    
    if __name__ == '__main__':
        node1 = TreeNode(2)
        node1.left = TreeNode(-5)
        node1.right = TreeNode(1)
    
        node3 = TreeNode(7)
        node3.left = TreeNode(9)
        node3.right = TreeNode(-7)
    
        node2 = TreeNode(8)
        node2.left = node1
        node2.right = node3
    
        s = Solution()
        res = s.findFrequentTreeSum(node2)
        print res
    
    
  • 相关阅读:
    统计英文文章单词出现的频率
    验证码程序
    随机出题程序
    Toast提示和Menu菜单
    Failed to resolve:com.android.support:appcompat-v7第一次运行安卓程序报错
    Android stdio下载与安装教学
    简单的三级联动
    河北省科技创新平台涉众分析(交流讨论)
    项目目标文档
    系统利益相关者描述案例
  • 原文地址:https://www.cnblogs.com/khal-Cgg/p/10019463.html
Copyright © 2011-2022 走看看