LeetCode-501. Find Mode in Binary Search Tree
阿新 • • 發佈:2019-01-24
問題:https://leetcode.com/problems/find-mode-in-binary-search-tree/?tab=Description
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. 給一個二叉搜尋樹,求出現次數最多的數是哪個。
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
1
\
2
/
2
return [2].
分析:
首先,tempCount++表示當前的數字出現次數+1,如果當前結點的值不等於儲存的值,就更新currentVal的值,並且將tempCount標記為1。
接下來,如果tempCount即當前數字出現的次數大於maxCount,就更新maxCount,並且將result陣列清零,並將當前數字放入result陣列中;如果tempCount只是等於maxCount,說明是出現次數一樣的,則將當前數字直接放入result陣列中。
參考C++程式碼:
/**
* 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) {
inorder(root);
return result;
}
private:
vector<int> result;
int maxcount=0;
int tem=0;
int cur=0;
void inorder(TreeNode* root){
if(NULL==root) return;
inorder(root->left);
tem++;
if(root->val!=cur){
cur=root->val;
tem=1;
}
if(tem>maxcount){
maxcount=tem;
result.clear();
result.push_back(root->val);
}
else if(tem==maxcount){
result.push_back(root->val);
}
inorder(root->right);
}
};