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
  | 
#include <cstddef>
#include <vector>
using std::vector;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
    void dfs(TreeNode *node, int &last, int &count, int &max_count, vector<int> &result)
    {
        if (node == nullptr)
            return;
        dfs(node->left, last, count, max_count, result);
        auto current = node->val;
        if (current == last)
        {
            count += 1;
        }
        else
        {
            count = 1;
        }
        if (count == max_count)
        {
            result.push_back(current);
        }
        else if (count > max_count)
        {
            max_count = count;
            result.clear();
            result.push_back(current);
        }
        last = current;
        dfs(node->right, last, count, max_count, result);
    }
    vector<int> findMode(TreeNode *root)
    {
        if (root == nullptr)
            return {};
        int last = 0, count = 0, max_count = 0;
        vector<int> result;
        dfs(root, last, count, max_count, result);
        return result;
    }
};
 
  |