/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> findMode(TreeNode *root) {
predecessorVal = -200000;
repeatCnt = 1;
maxRepeat = 1;
dfs(root);
return answer;
}
private:
int predecessorVal;
int repeatCnt;
int maxRepeat;
vector<int> answer;
void dfs(TreeNode *root) {
if (root == nullptr) {
return;
}
dfs(root->left);
if (predecessorVal == root->val) {
++repeatCnt;
} else {
repeatCnt = 1;
}
if (maxRepeat < repeatCnt) {
maxRepeat = repeatCnt;
answer.clear();
answer.push_back(root->val);
} else if (maxRepeat == repeatCnt) {
answer.push_back(root->val);
}
predecessorVal = root->val;
dfs(root->right);
}
};
root
.
root
.
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up