博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 508. Most Frequent Subtree Sum
阅读量:5172 次
发布时间:2019-06-13

本文共 1961 字,大约阅读时间需要 6 分钟。

题目链接

题目描述

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.

题解

递归遍历每一个节点,计算子树的所有节点的和,然后用一个map存起来,如果当前sum出现的次数最大,那就清空已有的sum;如果当前sum的次数和已有的sum个数相等,就把该sum添加进数组,并保存在map里面。

代码

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    private int maxCount = 0;    public int[] findFrequentTreeSum(TreeNode root) {        Map
map = new HashMap<>(); List
list = new ArrayList<>(); push(map, root, list); int[] a = new int[list.size()]; for (int i = 0; i < list.size(); i++) { a[i] = list.get(i); } return a; } public int push(Map
map, TreeNode root, List
list) { if (root == null) { return 0; } int left = push(map, root.left, list); int right = push(map, root.right, list); int sum = left + right + root.val; int count = map.getOrDefault(sum, 0) + 1; if (count > maxCount) { list.clear(); list.add(sum); maxCount = count; } else if (count == maxCount) { list.add(sum); } map.put(sum, count); return sum; }}

转载于:https://www.cnblogs.com/xiagnming/p/9591674.html

你可能感兴趣的文章
windows下的C++ socket服务器(4)
查看>>
css3 2d转换3d转换以及动画的知识点汇总
查看>>
计算机改名导致数据库链接的诡异问题
查看>>
Java8内存模型—永久代(PermGen)和元空间(Metaspace)(转)
查看>>
centos 引导盘
查看>>
Notes of Daily Scrum Meeting(12.8)
查看>>
Apriori算法
查看>>
onlevelwasloaded的调用时机
查看>>
lr_start_transaction/lr_end_transaction事物组合
查看>>
CodeIgniter学习笔记(四)——CI超级对象中的load装载器
查看>>
.NET CLR基本术语
查看>>
ubuntu的home目录下,Desktop等目录消失不见
查看>>
建立,查询二叉树 hdu 5444
查看>>
[Spring框架]Spring 事务管理基础入门总结.
查看>>
2017.3.24上午
查看>>
Python-常用模块及简单的案列
查看>>
LeetCode 159. Longest Substring with At Most Two Distinct Characters
查看>>
基本算法概论
查看>>
jquery动态移除/增加onclick属性详解
查看>>
JavaScript---Promise
查看>>