Skip to content

feat: add solutions to lc problem: No.0508 #3570

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 75 additions & 87 deletions solution/0500-0599/0508.Most Frequent Subtree Sum/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,13 @@ tags:

<!-- solution:start -->

### 方法一
### 方法一:哈希表 + DFS

我们可以使用一个哈希表 $\textit{cnt}$ 记录每个子树元素和出现的次数,然后使用深度优先搜索遍历整棵树,统计每个子树的元素和,并更新 $\textit{cnt}$。

最后,我们遍历 $\textit{cnt}$,找到所有出现次数最多的子树元素和。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。

<!-- tabs:start -->

Expand All @@ -72,19 +78,19 @@ tags:
# self.left = left
# self.right = right
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
def dfs(root):
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
left, right = dfs(root.left), dfs(root.right)
s = root.val + left + right
counter[s] += 1
l, r = dfs(root.left), dfs(root.right)
s = l + r + root.val
cnt[s] += 1
return s

counter = Counter()
cnt = Counter()
dfs(root)
mx = max(counter.values())
return [k for k, v in counter.items() if v == mx]
mx = max(cnt.values())
return [k for k, v in cnt.items() if v == mx]
```

#### Java
Expand All @@ -106,33 +112,26 @@ class Solution:
* }
*/
class Solution {
private Map<Integer, Integer> counter;
private Map<Integer, Integer> cnt = new HashMap<>();
private int mx;

public int[] findFrequentTreeSum(TreeNode root) {
counter = new HashMap<>();
mx = Integer.MIN_VALUE;
dfs(root);
List<Integer> res = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
if (entry.getValue() == mx) {
res.add(entry.getKey());
List<Integer> ans = new ArrayList<>();
for (var e : cnt.entrySet()) {
if (e.getValue() == mx) {
ans.add(e.getKey());
}
}
int[] ans = new int[res.size()];
for (int i = 0; i < res.size(); ++i) {
ans[i] = res.get(i);
}
return ans;
return ans.stream().mapToInt(i -> i).toArray();
}

private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int s = root.val + dfs(root.left) + dfs(root.right);
counter.put(s, counter.getOrDefault(s, 0) + 1);
mx = Math.max(mx, counter.get(s));
mx = Math.max(mx, cnt.merge(s, 1, Integer::sum));
return s;
}
}
Expand All @@ -154,26 +153,26 @@ class Solution {
*/
class Solution {
public:
unordered_map<int, int> counter;
int mx = 0;

vector<int> findFrequentTreeSum(TreeNode* root) {
mx = INT_MIN;
unordered_map<int, int> cnt;
int mx = 0;
function<int(TreeNode*)> dfs = [&](TreeNode* root) -> int {
if (!root) {
return 0;
}
int s = root->val + dfs(root->left) + dfs(root->right);
mx = max(mx, ++cnt[s]);
return s;
};
dfs(root);
vector<int> ans;
for (auto& entry : counter)
if (entry.second == mx)
ans.push_back(entry.first);
for (const auto& [k, v] : cnt) {
if (v == mx) {
ans.push_back(k);
}
}
return ans;
}

int dfs(TreeNode* root) {
if (!root) return 0;
int s = root->val + dfs(root->left) + dfs(root->right);
++counter[s];
mx = max(mx, counter[s]);
return s;
}
};
```

Expand All @@ -188,29 +187,26 @@ public:
* Right *TreeNode
* }
*/
func findFrequentTreeSum(root *TreeNode) []int {
counter := make(map[int]int)
mx := 0
var dfs func(root *TreeNode) int
func findFrequentTreeSum(root *TreeNode) (ans []int) {
cnt := map[int]int{}
var mx int
var dfs func(*TreeNode) int
dfs = func(root *TreeNode) int {
if root == nil {
return 0
}
s := root.Val + dfs(root.Left) + dfs(root.Right)
counter[s]++
if mx < counter[s] {
mx = counter[s]
}
cnt[s]++
mx = max(mx, cnt[s])
return s
}
dfs(root)
var ans []int
for k, v := range counter {
for k, v := range cnt {
if v == mx {
ans = append(ans, k)
}
}
return ans
return
}
```

Expand All @@ -232,26 +228,22 @@ func findFrequentTreeSum(root *TreeNode) []int {
*/

function findFrequentTreeSum(root: TreeNode | null): number[] {
const map = new Map<number, number>();
let max = 0;
const dfs = (root: TreeNode | null) => {
if (root == null) {
const cnt = new Map<number, number>();
let mx = 0;
const dfs = (root: TreeNode | null): number => {
if (!root) {
return 0;
}
const { val, left, right } = root;
const sum = val + dfs(left) + dfs(right);
map.set(sum, (map.get(sum) ?? 0) + 1);
max = Math.max(max, map.get(sum));
return sum;
const s = val + dfs(left) + dfs(right);
cnt.set(s, (cnt.get(s) ?? 0) + 1);
mx = Math.max(mx, cnt.get(s)!);
return s;
};
dfs(root);
const res = [];
for (const [k, v] of map) {
if (v === max) {
res.push(k);
}
}
return res;
return Array.from(cnt.entries())
.filter(([_, c]) => c === mx)
.map(([s, _]) => s);
}
```

Expand Down Expand Up @@ -279,33 +271,29 @@ function findFrequentTreeSum(root: TreeNode | null): number[] {
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
impl Solution {
fn dfs(
root: &Option<Rc<RefCell<TreeNode>>>,
map: &mut HashMap<i32, i32>,
max: &mut i32,
) -> i32 {
if root.is_none() {
return 0;
}
let node = root.as_ref().unwrap().borrow();
let sum = node.val + Self::dfs(&node.left, map, max) + Self::dfs(&node.right, map, max);
map.insert(sum, map.get(&sum).unwrap_or(&0) + 1);
*max = (*max).max(map[&sum]);
sum
}

impl Solution {
pub fn find_frequent_tree_sum(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut map = HashMap::new();
let mut max = 0;
let mut res = Vec::new();
Self::dfs(&root, &mut map, &mut max);
for (k, v) in map.into_iter() {
if v == max {
res.push(k);
fn dfs(root: Option<Rc<RefCell<TreeNode>>>, cnt: &mut HashMap<i32, i32>) -> i32 {
if let Some(node) = root {
let l = dfs(node.borrow().left.clone(), cnt);
let r = dfs(node.borrow().right.clone(), cnt);
let s = l + r + node.borrow().val;
*cnt.entry(s).or_insert(0) += 1;
s
} else {
0
}
}
res

let mut cnt = HashMap::new();
dfs(root, &mut cnt);

let mx = cnt.values().cloned().max().unwrap_or(0);
cnt.into_iter()
.filter(|&(_, v)| v == mx)
.map(|(k, _)| k)
.collect()
}
}
```
Expand Down
Loading
Loading