-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path501. Find Mode in Binary Search Tree (easy)
58 lines (48 loc) · 1.48 KB
/
501. Find Mode in Binary Search Tree (easy)
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
/**
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.
* 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 {
Integer pre;
int max = Integer.MIN_VALUE;
int cnt = 0;
public int[] findMode(TreeNode root) {
List<Integer> ans = new ArrayList<>();
inorder(root, ans);
int[] res = new int[ans.size()];
for (int i = 0; i < ans.size(); i++) res[i] = ans.get(i);
return res;
}
public void inorder(TreeNode root, List<Integer> ans) {
if (root == null) return;
inorder(root.left, ans);
if (pre == null || root.val != pre) cnt = 1;
else if (pre == null || root.val == pre) cnt++;
pre = root.val;
if (cnt > max) {
ans.clear();
ans.add(pre);
max = cnt;
}
else if (cnt == max){
ans.add(pre);
}
inorder(root.right, ans);
}
}