leetcode-501. 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).
思路:
1.递归记录每个节点,同时返回最大的相同节点数。
2.使用map 哈希思想是解决这种题目的最好选择
Accepted Code:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> findMode(TreeNode* root) { 13 unordered_map<int,int> mp; 14 vector<int> result; 15 int modeCount=getModeCount(root,mp); 16 17 for(pair<int,int> p:mp) 18 { 19 if(p.second==modeCount) 20 result.push_back(p.first); 21 } 22 return result; 23 } 24 25 int getModeCount(TreeNode* root,unordered_map<int,int>& mp) 26 { 27 if(root==nullptr) 28 return 0; 29 if(mp.find(root->val)==mp.end()) 30 { 31 mp.insert(pair<int,int>(root->val,1)); 32 }else 33 { 34 mp[root->val]++; 35 } 36 return max(mp[root->val],max(getModeCount(root->left,mp),getModeCount(root->right,mp))); 37 } 38 };