LeetCode 501 二叉搜索树的众数

    技术2022-07-12  61

    题目描述: 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

    假定 BST 有如下定义:

    结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜索树 例如: 给定 BST [1,null,2,2],

    1 2 / 2 返回[2].

    思路: 二叉搜索树的中序遍历是升序 因此先中序遍历 然后再找寻数组中的众数

    代码如下:

    /** * 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>temp; vector<int>res; int curtime=1; int maxtime=1; void dfs(TreeNode* root){ if(!root) return; dfs(root->left); temp.push_back(root->val); dfs(root->right); } vector<int> findMode(TreeNode* root) { dfs(root); if(temp.size()==0) return res; res.push_back(temp[0]); for(int i=1;i<temp.size();i++){ if(temp[i]==temp[i-1]) curtime++; else curtime=1; if(curtime==maxtime) res.push_back(temp[i]); else if (curtime>maxtime){ res.clear(); maxtime=curtime; res.push_back(temp[i]); } } return res; } };
    Processed: 0.012, SQL: 10