友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
501. Find Mode in Binary Search Tree
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
-
The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
-
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
-
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2]
,
1
\
2
/
2
return [2]
.
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
思路分析
看到二叉搜索树,应该条件反射般想到二叉搜索树的中根遍历是有序的。
由于中根遍历有序的特性,那么相同的数字就会一起出现,在出现的时候,统计每个数字出现的次数即可。思想容易理解,重点是代码的实现。有两个地方可以稍微简化一下代码:
-
先更新要处理的数字及次数;
-
然后根据次数,就可以处理需要的结果。
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
/**
* 根据相同数字出现在一起的提示,写出来的。
*/
public int[] findMode(TreeNode root) {
if (root == null) {
return new int[0];
}
List<Integer> result = new ArrayList<>();
TreeNode baseNode = null;
int count = 0;
int maxCount = Integer.MIN_VALUE;
TreeNode cur = root;
TreeNode mostRight = null;
while (cur != null) {
mostRight = cur.left;
if (mostRight != null) {
while (mostRight.right != null && mostRight.right != cur) {
mostRight = mostRight.right;
}
if (mostRight.right == null) {
mostRight.right = cur;
cur = cur.left;
continue;
} else {
mostRight.right = null;
}
}
// 在这里,利用二叉搜索树中序遍历,序列是有序的特性
// 相同的数字就会出现在一起,这是统计每个数字的出现次数
// baseNode == null 第一次遍历到这里
// baseNode.val != cur.val 进行到下一个数字
if (baseNode == null || baseNode.val != cur.val) {
baseNode = cur;
count = 1;
} else {
count++;
}
if (count > maxCount) {
result.clear();
result.add(cur.val);
maxCount = count;
} else if (count == maxCount) {
result.add(cur.val);
}
cur = cur.right;
}
int[] nums = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
nums[i] = result.get(i);
}
return nums;
}