* 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> res;
int mx = 0, cnt = 1;
TreeNode *pre = NULL;
helper(root, pre, cnt, mx, res);
return res;
}
//res传引用我能理解,因为要对它做修改。pre, cnt, mx应该只要传值就可以了吧?但是是错的,三个&都不能删,为什么呢?
void helper(TreeNode *node, TreeNode* &pre, int &cnt, int &mx, vector<int> &res) {
if (!node) {
return;
}
helper(node->left, pre, cnt, mx, res);
if (pre) {
cnt = (pre->val == node->val) ? cnt + 1 : 1;
}
if (cnt >= mx) {
if (cnt > mx) {
res.clear();
}
res.push_back(node->val);
mx = cnt;
}
pre = node;
helper(node->right, pre, cnt, mx, res);
}
};