Skip to content
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

feat: create 501. 二叉搜索树中的众数.md #586

Merged
merged 1 commit into from
May 28, 2022
Merged
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
45 changes: 45 additions & 0 deletions 501. 二叉搜索树中的众数.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@

# [501. 二叉搜索树中的众数](https://leetcode.cn/problems/find-mode-in-binary-search-tree/)

- 队列 + 哈希表

```
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/

function findMode(root: TreeNode | null): number[] {
const queue: TreeNode[] = [root];
const frequencyMap: Map<number, number> = new Map<number, number>();
let maxFrequency: number = 0;

while(queue.length) {
// 访问节点
const current = queue.pop();
// 记录频率
frequencyMap.set(current.val, (frequencyMap.get(current.val) ?? 0) + 1);
// 统计最大值
maxFrequency = Math.max(maxFrequency, frequencyMap.get(current.val));

current.left && queue.push(current.left);
current.right && queue.push(current.right);
}

return [...frequencyMap.keys()].reduce((results, key) => {
if(frequencyMap.get(key) === maxFrequency) {
results.push(key);
}
return results;
}, [])
};
```