[Swift]LeetCode508. 出现次数最多的子树元素和 | 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.



给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。

示例 1
输入:

  5
 /  2   -3

返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。

示例 2
输入:

  5
 /  2   -5

返回 [2],只有 2 出现两次,-5 只出现 1 次。

提示: 假设任意子树元素和均可以用 32 位有符号整数表示。



Runtime: 64 ms

Memory Usage: 21.2 MB

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func findFrequentTreeSum(_ root: TreeNode?) -> [Int] {
16         var res:[Int] = [Int]()
17         var m:[Int:Int] = [Int:Int]()
18         var cnt:Int = 0
19         postorder(root, &m, &cnt)
20         for (key,val) in m
21         {
22             if val == cnt
23             {
24                 res.append(key)
25             }
26         }
27         return res
28     }
29
30     func postorder(_ node: TreeNode?,_ m:inout [Int:Int],_ cnt:inout Int) -> Int
31     {
32         if node == nil {return 0}
33         var left:Int = postorder(node!.left, &m, &cnt)
34         var right:Int = postorder(node!.right, &m, &cnt)
35         var sum = left + right + node!.val
36         if m[sum] == nil
37         {
38             m[sum] = 1
39         }
40         else
41         {
42             m[sum]! += 1
43         }
44         cnt = max(cnt, m[sum]!)
45         return sum
46     }
47 }


64ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func findFrequentTreeSum(_ root: TreeNode?) -> [Int] {
16         var result = [Int:Int]()
17         _ = _findFrequentTreeSum(root, &result)
18
19         let maxRepeat = result.values.max() ?? 0
20
21         return result.compactMap { key,value in
22             guard value == maxRepeat else { return nil }
23             return key
24         }
25     }
26
27     func _findFrequentTreeSum(_ root: TreeNode?,
28                               _ result: inout [Int:Int]) -> Int
29     {
30         guard let root = root else { return 0 }
31
32         var value = root.val
33         value += _findFrequentTreeSum(root.left, &result)
34         value += _findFrequentTreeSum(root.right, &result)
35
36         result[value] = (result[value] ?? 0) + 1
37
38         return value
39     }
40 }


76ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func findFrequentTreeSum(_ root: TreeNode?) -> [Int] {
16         guard let root = root else { return [] }
17
18         var counter = [Int : Int]()
19         func dfs(_ node: TreeNode?) -> Int {
20             guard let node = node else { return 0 }
21             let s = node.val + dfs(node.left) + dfs(node.right)
22             counter[s, default: 0] += 1
23             return s
24         }
25
26         dfs(root)
27         let kvs = counter.sorted(by: {$0.1 > $1.1})
28         let freq = kvs[0].value
29         var ret = [Int]()
30         for (s, f) in kvs {
31             if f == freq {
32                 ret.append(s)
33             }
34         }
35         return ret
36     }
37 }


84ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     var mp = [Int: Int]()
16
17 func postorder(_ root: TreeNode?) -> Int{
18     if (root == nil) {
19         return 0;
20     }
21
22     let left = postorder(root?.left);
23     let right = postorder(root?.right);
24
25     let sum = (root?.val)! + left + right;
26
27     if mp[sum] != nil {
28         mp[sum]! += 1
29     } else {
30          mp[sum] =  1
31     }
32     return sum;
33 }
34
35
36 func findFrequentTreeSum(_ root: TreeNode?) -> [Int] {
37     postorder(root)
38     print(mp)
39     var fq = [Int]()
40     var max = Int.min
41     for number in mp.values {
42         if max < number {
43             max = number
44         }
45     }
46
47     for (i,number) in mp {
48         if max == number {
49             fq.append(i)
50         }
51     }
52
53    return fq
54   }
55 }


104ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func findFrequentTreeSum(_ root: TreeNode?) -> [Int] {
16         var map = [Int: Int]()
17         traverse(root, &map)
18
19         var result = [Int]()
20         var max = 0
21         for (sum, count) in map {
22             if count == max {
23                 result.append(sum)
24             } else if count > max {
25                 result.removeAll()
26                 max = count
27                 result.append(sum)
28             }
29         }
30         return result
31     }
32
33     private func traverse(_ node: TreeNode?, _ map: inout [Int: Int]) -> Int {
34         guard let node = node else { return 0 }
35
36         let sum = node.val + traverse(node.left, &map) + traverse(node.right, &map)
37         map[sum, default: 0] += 1
38
39         return sum
40     }
41 }


108ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14
15 class Solution {
16
17     func recordSubTreeSums(_ root: TreeNode?, _ subTreeSumMap: inout Dictionary<Int, Int>) -> Int {
18
19         guard let node = root else { return 0 }
20
21         let subTreeSum =    recordSubTreeSums(node.left, &subTreeSumMap) +
22                             recordSubTreeSums(node.right, &subTreeSumMap) +
23                             node.val
24
25         if let count = subTreeSumMap[subTreeSum] {
26             subTreeSumMap[subTreeSum] = count + 1
27         } else {
28             subTreeSumMap[subTreeSum] = 1
29         }
30
31         return subTreeSum
32     }
33
34     func findFrequentTreeSum(_ root: TreeNode?) -> [Int] {
35
36         var subTreeSumMap:Dictionary<Int, Int> = [:]
37         var result:[Int] = []
38
39         recordSubTreeSums(root, &subTreeSumMap)
40
41         var maxCount = -1
42
43         for key in subTreeSumMap.keys {
44             if let count = subTreeSumMap[key] {
45                 if (count > maxCount) { maxCount = count }
46             }
47         }
48
49         for key in subTreeSumMap.keys {
50             if let count = subTreeSumMap[key] {
51                 if (count == maxCount) { result = result + [key] }
52             }
53         }
54
55         return result
56     }
57 }

原文地址:https://www.cnblogs.com/strengthen/p/10392404.html

时间: 2024-12-12 02:03:29

[Swift]LeetCode508. 出现次数最多的子树元素和 | Most Frequent Subtree Sum的相关文章

1152: 零起点学算法59——找出一个数组中出现次数最多的那个元素

1152: 零起点学算法59--找出一个数组中出现次数最多的那个元素 Time Limit: 1 Sec  Memory Limit: 64 MB   64bit IO Format: %lldSubmitted: 990  Accepted: 532[Submit][Status][Web Board] Description 找出一个数组中出现次数最多的那个元素 Input 第一行输入一个整数n(不大于20) 第二行输入n个整数 多组数据 Output 找出n个整数中出现次数最多的那个整数(

找出一个数组中出现次数最多的那个元素

#include <stdio.h> int main() { int n,a[20],i,j,flag=0,max; int b[20]={0}; while(scanf("%d",&n)==1){ if(n==0) break; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(a[i]==a[j]) b[i]++

[leetcode]508. Most Frequent Subtree Sum二叉树中出现最多的值

遍历二叉树,用map记录sum出现的次数,每一个新的节点都统计一次. 遍历完就统计map中出现最多的sum Map<Integer,Integer> map = new HashMap<>(); public int[] findFrequentTreeSum(TreeNode root) { helper(root); int max = 0; List<Integer> list = new ArrayList<>(); for (int key : m

[LeetCode] 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

508. 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 fre

算法训练 出现次数最多的整数

整数超出int范围了,改成字符型判断才过了. 时间限制:1.0s   内存限制:512.0MB 问题描述 编写一个程序,读入一组整数,这组整数是按照从小到大的顺序排列的,它们的个数N也是由用户输入的,最多不会超过20.然后程序将对这个数组进行统计,把出现次数最多的那个数组元素值打印出来.如果有两个元素值出现的次数相同,即并列第一,那么只打印比较小的那个值. 输入格式:第一行是一个整数N,N? £? 20:接下来有N行,每一行表示一个整数,并且按照从小到大的顺序排列. 输出格式:输出只有一行,即出

20-算法训练 出现次数最多的整数

http://lx.lanqiao.cn/problem.page?gpid=T222 算法训练 出现次数最多的整数 时间限制:1.0s   内存限制:512.0MB 问题描述 编写一个程序,读入一组整数,这组整数是按照从小到大的顺序排列的,它们的个数N也是由用户输入的,最多不会超过20.然后程序将对这个数组进行统计,把出现次数最多的那个数组元素值打印出来.如果有两个元素值出现的次数相同,即并列第一,那么只打印比较小的那个值. 输入格式:第一行是一个整数N,N? £? 20:接下来有N行,每一行

python之Counter类:计算序列中出现次数最多的元素

Counter类:计算序列中出现次数最多的元素 1 from collections import Counter 2 3 c = Counter('abcdefaddffccef') 4 print('完整的Counter对象:', c) 5 6 a_times = c['a'] 7 print('元素a出现的次数:', a_times) 8 9 c_most = c.most_common(3) 10 print('出现次数最多的三个元素:', c_most) 11 12 times_dic

华为机试—整型数组中出现次数最多的元素

取出整型数组中出现次数最多的元素,并按照升序排列返回. 要求实现方法: public static int[] calcTimes(int[] num, int len); [输入] num:整型数组: len :输入的整数个数 [返回] 按照升序排列返回整型数组中出现次数最多的元素 [注意]只需要完成该函数功能算法,中间不需要有任何IO的输入输出 示例 输入:num = {1,1,3,4,4,4,9,9,9,10} len = 10 返回:{4,9} #include <iostream>