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).
题目大意:求给定bst树种出现次数最多的数。
思路:中序遍历,记录先前结点的值和当前结点的值比较,并记录出现的次数。具体实现看代码。
/**
* 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> ans;
int Max = 0;
void dfs(TreeNode* root, int& pre, int& cn) {
if (root == nullptr) return ;
dfs(root->left, pre, cn);
if (root->val == pre) {
cn++;
} else if (pre != -1){
if (cn > Max) {
Max = cn;
ans.clear();
ans.emplace_back(pre);
//cout << root->val << endl;
} else if (cn == Max) {
ans.emplace_back(pre);
}
cn = 1;
}
//cout << root->val << endl;
pre = root->val;
dfs(root->right, pre, cn);
}
vector<int> findMode(TreeNode* root) {
int pre = -1;
int cn = 1;
if (root == nullptr) return ans;
dfs(root, pre, cn);
if (cn > Max) {
ans.clear();
ans.emplace_back(pre);
} else if (cn == Max) {
ans.emplace_back(pre);
}
return ans;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: