LeetCode 235.二叉搜索树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) {
return root;
}
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if(left && right) {
return root;
} else if(left) {
return left;
} else {
return right;
}
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root->val > p->val && root->val > q->val) {
return lowestCommonAncestor(root->left, p, q);
}
if(root->val < p->val && root->val < q->val) {
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};
LeetCode 701.二叉搜索树中的插入操作
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) {
auto new_node = new TreeNode(val);
return new_node;
}
if(root->val > val) {
root->left = insertIntoBST(root->left, val);
} else {
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) {
auto new_node = new TreeNode(val);
return new_node;
}
auto cur = root, parent = root;
while(cur != nullptr) {
parent = cur;
if(cur->val > val) {
cur = cur->left;
} else {
cur = cur->right;
}
}
auto new_node = new TreeNode(val);
if(parent->val > val) {
parent->left = new_node;
} else {
parent->right = new_node;
}
return root;
}
};
LeetCode 450.删除二叉搜索树中的节点
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr) {
return root;
}
if(root->val == key) {
if(root->left == nullptr && root->right == nullptr) {
delete root;
return nullptr;
}
if(root->left != nullptr && root->right == nullptr) {
auto ret_node = root->left;
delete root;
return ret_node;
}
if(root->left == nullptr && root->right != nullptr) {
auto ret_node = root->right;
delete root;
return ret_node;
}
if(root->left != nullptr && root->right != nullptr) {
auto cur = root->right;
while(cur->left != nullptr) {
cur = cur->left;
}
cur->left = root->left;
auto tmp = root;
root = root->right;
delete tmp;
return root;
}
}
if (root->val > key) root->left = deleteNode(root->left, key);
if (root->val < key) root->right = deleteNode(root->right, key);
return root;
}
};