day20 二叉樹7
235. 二叉搜索樹的最近公共祖先
遞歸法:
class Solution {
public:
TreeNode* traversal(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur->val > p->val && cur->val > q->val) {
TreeNode* left = traversal(cur->left, p, q);
if (left != nullptr) {
return left;
}
}
if (cur->val < p->val && cur->val < q->val) {
TreeNode* right = traversal(cur->right, p, q);
if (right != nullptr) {
return right;
}
}
return cur;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return traversal(root, p, q);
}
};
迭代法:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (root) {
if (root->val < p->val && root->val < q->val) {
root = root->right;
}
else if (root->val > p->val && root->val > q->val) {
root = root->left;
}
else {
return root;
}
}
return root;
}
};
701.二叉搜索樹中的插入操作
遞歸法:
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;
}
};
迭代法:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode *node = new TreeNode(val);
if (root == nullptr) {
return node;
}
TreeNode *cur = root;
TreeNode *parent = root;
while (cur) {
parent = cur;
if (cur->val > val) {
cur = cur->left;
}
else {
cur = cur->right;
}
}
if (val < parent->val) {
parent->left = node;
}
else {
parent->right = node;
}
return root;
}
};
450.刪除二叉搜索樹中的節(jié)點(diǎn)
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;
}
//左空,右不空
else if (root->left == nullptr) {
auto right = root->right;
delete root;
return right;
}
//左不空唧垦,右空
else if (root->right == nullptr) {
auto left = root->left;
delete root;
return left;
}
//左不空,右不空
else {
TreeNode* cur = root->right;
while (cur->left != nullptr) {
cur = cur->left;
}
cur->left = root->left;
root = root->right;
return root;
}
}
if (root->val > key) {
root->left = deleteNode(root->left, key);
}
if (root->val < key) {
root->right = deleteNode(root->right, key);
}
return root;
}
};