LeetCode题解之 Find Mode in Binary Search Tree

二叉树众数查找算法
本文介绍了一种使用map记录元素出现次数的算法,通过先序遍历二叉树来找出树中出现频率最高的元素(众数)。该算法首先遍历整个二叉树并记录每个节点值出现的次数,然后找出最高频率的数值并将其存入结果向量中。

1、题目描述

 

2、问题分析

使用map记录元素出现的次数。

 

3、代码

 1 vector<int> v;
 2     map<int,int> m;
 3     vector<int> findMode(TreeNode* root) {
 4         if (root == NULL)
 5             return v;
 6         preOrder(root);
 7         int n = 0;
 8         for(map<int,int>::iterator it = m.begin(); it != m.end(); it++) {
 9             if (it->second >= n)
10                 n = it->second;
11         }
12         
13         for(map<int, int>::iterator it = m.begin(); it != m.end(); it++) {
14             if (it->second == n)
15                 v.push_back(it->first);
16         }
17         
18         return v;
19     }
20     
21     void preOrder(TreeNode *root)
22     {
23         if (root != NULL)
24             m[root->val]++;
25         else 
26             return;
27         preOrder(root->left);
28         preOrder(root->right);
29     }

 

转载于:https://www.cnblogs.com/wangxiaoyong/p/10460024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值