一、验证二叉搜索树
class Solution {
public:
bool isvaild(TreeNode* root, long low, long upper) {
if (root == nullptr)
return true;
if (root->val <= low || root->val >= upper)
return false;
return isvaild(root->left, low, root->val) &&
isvaild(root->right, root->val, upper);
}
bool isValidBST(TreeNode* root) {
return isvaild(root, LONG_MIN, LONG_MAX);
}
};
二、二叉搜索树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
if (left) return left;
return right;
}
};