Q:
A:
首先这题可以遍历一遍二叉树,用一个map来存每个数字出现的次数之后取最大的就行,但这样没有利用到二叉搜索树的条件。所以我们利用二叉搜索树中序遍历升序(此题中为非降序)的性质,保存中序前缀节点,若当前节点与前缀节点值相同,计数+1,若不同则重新从0开始计数。因为是非降序,所以一旦遍历到了一个更大的数字,之后的数字都只会相同或更大。额外维持一个全局变量maxsize记录目前为止的出现最多数字的出现次数,视情况更新maxsize和结果数组。
迭代版:
/**
* 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) {
if(root==0){
return vector<int>();
}
vector<int> res;
stack<TreeNode*> sta;
TreeNode* cur=root,*pre_cur=0;
int cur_size=0,max_size=0;
while(cur or !sta.empty()){
if(cur){
sta.push(cur);
cur=cur->left;
}
else{
cur=sta.top();
sta.pop();
if(pre_cur and cur->val==pre_cur->val){
cur_size++;
}
else{
cur_size=1;
}
if(cur_size>max_size){
max_size=cur_size;
res.clear();
res.push_back(cur->val);
}
else if(cur_size==max_size){
res.push_back(cur->val);
}
pre_cur=cur;
cur=cur->right;
}
}
return res;
}
};
递归版
/**
* 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) {
if(root==0){
return vector<int>();
}
int maxsize=0,cursize=0;
vector<int> res;
TreeNode* pre_root=0;
helper(root,res,maxsize,cursize,pre_root);
return res;
}
void helper(TreeNode* root,vector<int>& res,int& maxsize,int& cursize,TreeNode*& pre_root){//中序遍历
if(root->left){
helper(root->left,res,maxsize,cursize,pre_root);
}
if(pre_root and pre_root->val==root->val){
++cursize;
}
else{
cursize=1;
}
if(cursize>maxsize){
maxsize=cursize;
res.clear();
res.push_back(root->val);
}
else if(cursize==maxsize){
res.push_back(root->val);
}
pre_root=root;
if(root->right){
helper(root->right,res,maxsize,cursize,pre_root);
}
}
};