题目来源
查找二叉搜索树种出现次数最多的节点。
我直接采用最简单的方法,就是直接先把二叉树中序遍历。然后记录下目前为止出现次数最多的节点。
/**
* 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> findMode(TreeNode* root) {
vector<int> nums;
vector<int> res;
dfs(root, nums);
int m = 1, cur = 1;
if (nums.size() == 0)
return res;
res.push_back(nums[0]);
for (int i=1; i<nums.size(); i++) {
if (nums[i-1] == nums[i])
cur++;
else
cur = 1;
if (cur == m)
res.push_back(nums[i]);
if (cur > m) {
m = cur;
res.clear();
res.push_back(nums[i]);
}
}
return res;
}
void dfs(TreeNode *node, vector<int> &nums)
{
if (!node)
return;
dfs(node->left, nums);
nums.push_back(node->val);
dfs(node->right, nums);
}
};
然后搞了半天,怎么把vector搞掉,代码如下:
/**
* 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:
TreeNode *pre = NULL;
vector<int> findMode(TreeNode* root) {
vector<int> res;
int cur = 0, m = 1;
dfs(root, res, m, cur);
return res;
}
void dfs(TreeNode *node, vector<int> &res, int &m, int &cur)
{
if (!node)
return;
dfs(node->left, res, m, cur);
if (pre && node->val == pre->val)
cur++;
else
cur = 1;
if (cur == m)
res.push_back(node->val);
if (cur > m) {
m = cur;
res.clear();
res.push_back(node->val);
}
pre = node;
dfs(node->right, res, m, cur);
}
};