二叉搜索树的最小绝对差
class Solution {
public:
int result = INT_MAX;
int pre;
int getMinimumDifference(TreeNode* root) {
//初始化,避免未更新的pre与第一个值做差得到0
if(root->left)
pre = root->val;
else
pre =root->right->val;
inorder(root);
return result;
}
void inorder(TreeNode* root){
if(!root)
return;
if(root->left){
inorder(root->left);
}
result = min(abs(root->val - pre), result);
pre = root->val;
if(root->right){
inorder(root->right);
}
}
};
二叉搜索树中的众数
class Solution {
public:
int counts = 0;
int maxcounts = 0;
int pre;
vector<int> result;
vector<int> findMode(TreeNode* root) {
pre = root->val;
inorder(root);
return result;
}
void inorder(TreeNode* root){
if(root->left) inorder(root->left);
if(root->val == pre){
counts++;
if(maxcounts < counts){
maxcounts = counts;
result.clear();
result.push_back(root->val);
}
else if(maxcounts == counts){
result.push_back(root->val);
}
}
// 重新计数
else{
pre = root->val;
counts = 1;
// 避免全是1次出现
if(maxcounts < counts){
maxcounts = counts;
result.clear();
result.push_back(root->val);
}
else if(maxcounts == counts){
result.push_back(root->val);
}
}
if(root->right) inorder(root->right);
}
};
pre用Treenode进行初始化时可以减少很多讨论
二叉树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q || !root)
return root;
if(root->left && !root->right)
return lowestCommonAncestor(root->left, p, q);
if(root->right && !root->left)
return lowestCommonAncestor(root->right, p, q);
TreeNode* r = lowestCommonAncestor(root->right, p, q);
TreeNode* l = lowestCommonAncestor(root->left, p, q);
if(r && l)
return root;
if(!r && l)
return l;
if(!l && r)
return r;
return nullptr;//没有找到p||q
}
};