235. 二叉搜索树的最近公共祖先
题目链接:235. 二叉搜索树的最近公共祖先
文档链接:235. 二叉搜索树的最近公共祖先
视频链接:二叉搜索树找祖先就有点不一样了!| 235. 二叉搜索树的最近公共祖先
C++实现
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL) return NULL;
if(p->val < root->val && q->val < root->val){
TreeNode* left = lowestCommonAncestor(root->left, p,q);
if(left!= NULL) return left;
}
if(p->val > root->val && q->val > root->val){
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(right != NULL) return right;
}
return root;
}
};
701.二叉搜索树中的插入操作
题目链接:701.二叉搜索树中的插入操作
文档链接:701.二叉搜索树中的插入操作
视频链接:原来这么简单? | LeetCode:701.二叉搜索树中的插入操作
C++实现
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL){
root = new TreeNode(val);
return root;
}
if(val < root->val){
root->left = insertIntoBST(root->left, val);
}
if(val > root->val){
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
450.删除二叉搜索树中的节点
题目链接:450.删除二叉搜索树中的节点
文档链接:450.删除二叉搜索树中的节点
视频链接:调整二叉树的结构最难!| LeetCode:450.删除二叉搜索树中的节点
C++实现
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == NULL) return NULL;
if(root->val == key){
if(root->left == NULL && root->right == NULL) {
delete root;
return NULL;
}
else if(root->left != NULL && root->right == NULL) {
TreeNode* tmp = root;
root = root->left;
delete tmp;
return root;
}
else if(root->left == NULL && root->right != NULL) {
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
}
else if(root->left != NULL && root->right != NULL){
TreeNode* cur = root->right;
while(cur->left != NULL) cur = cur->left;
cur->left = root->left;
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
}
}
if(key < root->val) root->left = deleteNode(root->left, key);
if(key > root->val) root->right= deleteNode(root->right, key);
return root;
}
};