leetcode 501. 二叉搜索树中的众数(Find Mode in Binary Search
发布时间:2020-12-14 04:34:21 所属栏目:大数据 来源:网络整理
导读:目录 题目描述: 示例: 解法: 题目描述: 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左
目录
题目描述:给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假定 BST 有如下定义:
示例:给定 BST 1 2 / 2 返回[2]. 提示:如果众数超过1个,不需考虑输出顺序 进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内) 解法:/** * 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: void inOrder(TreeNode* root,TreeNode*& pre,int& curTimes,int& maxTimes,vector<int>& res){ if (!root) return; inOrder(root->left,pre,curTimes,maxTimes,res); if (pre) curTimes = (root->val == pre->val) ? curTimes + 1 : 1; if (curTimes == maxTimes) res.push_back(root->val); else if (curTimes > maxTimes){ res.clear(); res.push_back(root->val); maxTimes = curTimes; } pre = root; inOrder(root->right,res); } vector<int> findMode(TreeNode* root) { vector<int> res; if (!root) return res; TreeNode* pre = NULL; int curTimes = 1,maxTimes = 0; inOrder(root,res); return res; } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |