https://leetcode.com/problems/find-mode-in-binary-search-tree/description/
Solution 1: In-order traversal
mx: max count of different values
cnt: counting the duplicates
preVal: previous checked value
void inOrder(TreeNode* node, vector<int>& mode, int& mx, int& cnt, int& preVal) {
if(!node) return;
inOrder(node->left, mode, mx, cnt, preVal);
if(cnt == 0) {
cnt = 1;
preVal = node->val;
}
else if(node->val == preVal) cnt++;
else {
if(mx == cnt) mode.push_back(preVal);
else if(mx < cnt) {
mx = cnt;
mode.clear();
mode.push_back(preVal);
}
preVal = node->val;
cnt = 1;
}
inOrder(node->right, mode, mx, cnt, preVal);
}
vector<int> findMode(TreeNode* root) {
vector<int> mode;
if(!root) return mode;
int mx = 0, cnt = 0, preVal;
inOrder(root, mode, mx, cnt, preVal);
if(mx < cnt) return {preVal};
if(mx == cnt) mode.push_back(preVal);
return mode;
}
Solution 2. We can always do an in-order tree traversal and store the numbers in an array and then search for the mode.
No comments:
Post a Comment