标签:tar 中序 color res must tor ptr extra tps
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:
For example:
Given BST [1,null,2,2]
,
1 2 / 2
return [2]
.
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
找出二叉搜索树中最常见的元素。因为题目要求是严格的二叉搜索树。想了一个简单但是效率很低的方法。
首先中序遍历二叉搜索树存入一个数组中,然后将数组元素放去map统计出现的最大次数。最后在遍历一个map把最常见的元素放去结果数组中。
/** * 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> inorder; vector<int> findMode(TreeNode* root) { unordered_map<int, int> m; vector<int> res; dfs(root); int cnt = 0; for (auto n : inorder) m[n]++; for (auto it = m.begin(); it != m.end(); it++) { if (it->second > cnt) cnt = it->second; } for (auto it = m.begin(); it != m.end(); it++) { if (it->second == cnt) { res.push_back(it->first); } } return res; } vector<int> dfs(TreeNode* root) { if (root == nullptr) return inorder; dfs(root->left); inorder.push_back(root->val); dfs(root->right); return inorder; } }; // 59 ms
[LeetCode] Find Mode in Binary Search Tree
标签:tar 中序 color res must tor ptr extra tps
原文地址:http://www.cnblogs.com/immjc/p/7554403.html