当前位置:网站首页>Mode in BST (binary tree & Notes on question brushing)

Mode in BST (binary tree & Notes on question brushing)

2022-07-05 04:32:00 Toolman firefly

Violence statistics . Common tree practice , Roll it first , Let's look at the specific frequency

  • map: The internal is RB Trees , The output is orderly .
  • unordered_map yes hash function , Output disorder
private:
	unordered_map<int,int> mp;
public:
	void dfs(TreeNode* cur_node)
	{
    
		if(cur_node==nullptr)	return ;
		mp[cur_node->val]++;
		dfs(cur_node->left);
		dfs(cur_node->right);
	}
	bool static cmp(const pair<int,int>&a,const pair<int,int>&b) 
	{
    
		return a.second>b.second;
	}
	vector<int>	FindNode(TreeNode* root)
	{
    
		vector<int> res;
		if(root==nullptr)	return ;
		dfs(root);
		
		vector<pair<int,int>> vec(mp.begin(),mp.end());/* Very important */
		sort(vec.begin(),vec.end(),cmp);/* Note the return value of the function */
		res.push_back(vec[0].first);
		for(int i=1;i<vec.size();i++)
		{
    
			if(vec[i].second==vec[0].second)
				res.push_back(vec[i].first);
			else
				break;
		}
		return res;
	}

Because of the mention of BST We're going to use BST Characteristics of ,BST Middle order traversal of , Is an ascending array

private:
	int count;
	int max_count;
	TreeNode* pre_node;
	vector<int> res;
public:
	void dfs(TreeNode* cur_node);
	{
    
		if(cur_node==nullptr)	return;
		dfs(cur_node->left);/*================================ Left */
		
		if(pre_node==nullptr)	count=1;/* First node */
		else if(pre_node->val==cur_node->val)	count++;/* The same value as the previous node */
		else	count=1;/* Different from the previous node value */
		
		pre_node=cur_node;/* Update is a node */
		
		if(count==max_count)	res.push_back(cur->val);
		if(count>max_count)	{
    
			max_count=count;
			res.clear();
			res.push_baxk(cur_node->val);
		}

		dfs(cur_node->right);/*============================== Right */
	}
	vector<int> FindNode(TreeNode* root)
	{
    
		count=0;
		max_count=0;
		pre_node=nullptr;
		res={
    };
		
		dfs(root);
			
		return res;
	}
原网站

版权声明
本文为[Toolman firefly]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140636475358.html