Minimum Absolute Difference in BST的思路就是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:
int minre = INT_MAX;
TreeNode *prev=NULL;
int getMinimumDifference(TreeNode* root) {
if(root==NULL)
return minre;
getMinimumDifference(root->left);
if(prev!=NULL)
{
minre=min(minre,root->val-prev->val);
}
prev=root;
getMinimumDifference(root->right);
return minre;
}
};
Find Mode in Binary Search Tree的道理也是一樣的,還是中序遍歷,然後算每個數出現了幾次,找到出現次數最多的(用一個Count和CurrentCount,一個計算目前出現過的最大次數,另一個算當前數字出現的次數,兩個比)
/**
* 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> re;
int count=1;
int currentCount=1;
TreeNode *prev=NULL;
vector<int> findMode(TreeNode* root) {
if(root==NULL)
return re;
findMode(root->left);
if(prev!=NULL)
{
if(root->val==prev->val)
{
currentCount++;
if(currentCount==count)
{
re.push_back(prev->val);
}
else if(currentCount>count)
{
re.clear();
re.push_back(prev->val);
count=currentCount;
}
}
else
{
currentCount=1;
}
}
prev=root;
if(count==1)
{
re.push_back(root->val);
}
findMode(root->right);
return re;
}
};