-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0501.二叉搜索树中的众数.java
115 lines (106 loc) · 2.33 KB
/
0501.二叉搜索树中的众数.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* @lc app=leetcode.cn id=501 lang=java
*
* [501] 二叉搜索树中的众数
*
* https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
*
* algorithms
* Easy (54.83%)
* Likes: 718
* Dislikes: 0
* Total Accepted: 184.4K
* Total Submissions: 336.1K
* Testcase Example: '[1,null,2,2]'
*
* 给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
*
* 如果树中有不止一个众数,可以按 任意顺序 返回。
*
* 假定 BST 满足如下定义:
*
*
* 结点左子树中所含节点的值 小于等于 当前节点的值
* 结点右子树中所含节点的值 大于等于 当前节点的值
* 左子树和右子树都是二叉搜索树
*
*
*
*
* 示例 1:
*
*
* 输入:root = [1,null,2,2]
* 输出:[2]
*
*
* 示例 2:
*
*
* 输入:root = [0]
* 输出:[0]
*
*
*
*
* 提示:
*
*
* 树中节点的数目在范围 [1, 10^4] 内
* -10^5 <= Node.val <= 10^5
*
*
*
*
* 进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
*
*/
// @lc code=start
import java.util.ArrayList;
import java.util.List;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int base, count, maxCount;
private List<Integer> records = new ArrayList<>();
public int[] findMode(TreeNode root) {
dfs(root);
return records.stream().mapToInt(Integer::intValue).toArray();
}
private void dfs(TreeNode root) {
if (root == null)
return;
dfs(root.left);
update(root.val);
dfs(root.right);
}
private void update(int x) {
if (x == base)
count++;
else {
base = x;
count = 1;
}
if (count == maxCount)
records.add(base);
else if (count > maxCount) {
maxCount = count;
records.clear();
records.add(base);
}
}
}
// @lc code=end