二叉搜索树用中序遍历,遍历顺序是一个非严格单调递增的数组。
class Solution {
public:
int ans;
TreeNode* pre = nullptr;
void dfs(TreeNode* cur)
{
if (cur==nullptr) return;
dfs(cur->left);
if (pre!=nullptr) ans = min(ans, cur->val-pre->val);
pre = cur;
dfs(cur->right);
}
int getMinimumDifference(TreeNode* root)
{
ans = INT_MAX;
dfs(root);
return ans;
}
};
class Solution {
public:
TreeNode* pre = nullptr;
int maxnum = 0;
int val = 0;
int num = 0;
vector<int> ans;
void dfs(TreeNode* cur)
{
if (cur==nullptr) return;
dfs(cur->left);
if (pre != nullptr && pre->val==cur->val)
{
num++;
}
else
{
num=1;
val = cur->val;
}
if (num>=maxnum)
{
if (num>maxnum) ans.clear();
ans.push_back(cur->val);
maxnum = num;
}
pre =cur;
dfs(cur->right);
}
vector<int> findMode(TreeNode* root)
{
dfs(root);
return ans;
}
};
有一定难度,后面仔细看看
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (root == q || root == p || root == NULL) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) return root;
if (left == NULL && right != NULL) return right;
else if (left != NULL && right == NULL) return left;
else { // (left == NULL && right == NULL)
return NULL;
}
}
};