二叉搜索树的最小公共最先
总算是自己看了解析做出来了一道题,不过用了chatgpt帮忙
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL) return root;
TreeNode* left;
TreeNode* right;
if((root->val <= q->val and root->val >= p->val) || (root->val >= q->val and root->val <= p->val)) return root;
else if(root->val > q->val and root->val > p->val) {
left = lowestCommonAncestor(root->left, p, q);
if(left != NULL) return left;
return root;
}
else {
right = lowestCommonAncestor(root->right, p, q);
if(right != NULL) return right;
return root;
}
}
};
二叉搜索树插入
本题大致理解啦,主要就是要把新节点值插入在叶子节点的位置
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) {
TreeNode* node = new TreeNode(val);
return node;
}
if(root->val > val) root->left = insertIntoBST(root->left, val);
if(root->val < val) root->right = insertIntoBST(root->right, val);
return root;
}
};