501. Find Mode in Binary Search Tree
Posted 高数考了59
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了501. Find Mode in Binary Search Tree相关的知识,希望对你有一定的参考价值。
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 static int wing=[]() 11 { 12 std::ios::sync_with_stdio(false); 13 cin.tie(NULL); 14 return 0; 15 }(); 16 17 class Solution 18 { 19 public: 20 vector<int> findMode(TreeNode* root) 21 { 22 vector<int> res; 23 if(root==NULL) 24 return res; 25 queue<TreeNode*> q; 26 int maxcount=0; 27 TreeNode *p=root; 28 q.push(p); 29 unordered_map<int,int> itoi; 30 while(!q.empty()) 31 { 32 p=q.front(); 33 itoi[p->val]++; 34 maxcount=max(maxcount,itoi[p->val]); 35 q.pop(); 36 if(p->left) 37 q.push(p->left); 38 if(p->right) 39 q.push(p->right); 40 } 41 for(auto k:itoi) 42 if(k.second==maxcount) 43 res.push_back(k.first); 44 return res; 45 } 46 };
层次遍历,问题不大。可惜要用个辅助map,空间复杂度为O(n)
以上是关于501. Find Mode in Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
LeetCode_501. Find Mode in Binary Search Tree
501. Find Mode in Binary Search Tree - Easy
leetcode 501. Find Mode in Binary Search Tree