Leetcode 501. Find Mode in Binary Search Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Find Mode in Binary Search Tree

2. Solution

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> modes;
if(!root) {
return modes;
}
int count = 0;
int max = 0;
int prev = 0;
inorder(root, modes, count, max, prev);
return modes;
}

private:
void inorder(TreeNode* root, vector<int>& modes, int& count, int& max, int& prev) {
if(!root) {
return;
}
inorder(root->left, modes, count, max, prev);
if(root->val == prev) {
count++;
}
else {
count = 1;
}
if(count > max){
modes.clear();
max = count;
modes.push_back(root->val);
}
else if(count == max) {
modes.push_back(root->val);
}
prev = root->val;
inorder(root->right, modes, count, max, prev);
}
};

Reference

  1. https://leetcode.com/problems/find-mode-in-binary-search-tree/description/
如果有收获,可以请我喝杯咖啡!