LeetCode 501
Find Mode in Binary Search Tree
Problem Description:
返回二叉搜索树中出现最多次数的节点值的序列。
- Solution:
/**
* 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> result;
if (root == NULL) return result;
stack<TreeNode*> node;
vector<int> num;
TreeNode* p = root;
//用max记录遍历过程中出现最多次数节点值
int max = 0, count = 0, temp = 0;
while(p || !node.empty()) {
while(p) {
node.push(p);
p = p->left;
}
p = node.top();
num.push_back(p->val);
if (count == 0) {
temp = p->val;
count++;
} else {
if (temp == p->val) {
count++;
} else {
if (count>max)
max = count;
temp = p->val;
count = 1;
}
}
node.pop();
p = p->right;
}
if (count>max)
max = count;
count = 0, temp = num[0];
for (int i = 0; i < num.size(); i++) {
if (temp == num[i]) {
count++;
} else {
temp = num[i];
count = 1;
}
if (count == max)
result.push_back(num[i]);
}
return result;
}
};