[LeetCode] Find Mode in Binary Search Tree
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:
- The left subtree of a node contains only nodes with keys less than or equal to the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
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