首页 > 学院 > 开发设计 > 正文

leetcode-501-Find Mode in Binary Search Tree

2019-11-08 19:51:25
字体:
来源:转载
供稿:网友

问题

题目:[leetcode-501]

思路

常规题。遍历一遍,找出出现次数最大的值。 然后枚举哈希表即可。

代码

/** * 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) { std::vector<int> ret; if(!root) return ret; std::map<int, int> mapper; int max = 0; PReOrder(root,mapper,max); typedef std::map<int, int>::const_iterator const_iter; const_iter b = mapper.begin(); const_iter e = mapper.end(); while(b != e){ if(b->second==max) ret.push_back(b->first); ++b; } return ret; }private: void preOrder(TreeNode* root, std::map<int,int>& mapper, int& max){ if(!root) return ; int cnt = ++mapper[root->val]; max = std::max(max, cnt); preOrder(root->left, mapper, max); preOrder(root->right, mapper, max); }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表