-
Notifications
You must be signed in to change notification settings - Fork 1
/
501.find-mode-in-binary-search-tree.java
60 lines (56 loc) · 1.37 KB
/
501.find-mode-in-binary-search-tree.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
/*
* @lc app=leetcode id=501 lang=java
*
* [501] Find Mode in Binary Search Tree
*/
// @lc code=start
/**
* 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 {
int cur_len = 0;
int max_len = Integer.MIN_VALUE;
TreeNode prev = null;
ArrayList<Integer> resList = new ArrayList<>();;
public int[] findMode(TreeNode root) {
traverse(root);
int[] res = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
res[i] = resList.get(i);
}
return res;
}
private void traverse(TreeNode node) {
if (node == null) {
return;
}
traverse(node.left);
if (prev == null || prev.val != node.val) {
cur_len = 1;
} else {
cur_len++;
}
if (cur_len > max_len) {
resList.clear();
resList.add(node.val);
max_len = cur_len;
} else if (cur_len == max_len) {
resList.add(node.val);
}
prev = node;
traverse(node.right);
}
}
// @lc code=end