235.二叉搜索树的最近公共祖先
思路:递归遍历二叉搜索树
如果当前值大于p和q的值,向左遍历
如果当前值小于p和q的值,向右遍历
否则说明当前值介于p和q之间,直接返回当前节点
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr) return nullptr;
if(root->val > p->val && root->val > q->val) {
TreeNode* left = lowestCommonAncestor(root->left, p, q);
if(left) return left;
}
if(root->val < p->val && root->val < q->val) {
TreeNode*right = lowestCommonAncestor(root->right, p, q);
if(right) return right;
}
return root;
}
};
701.二叉搜索树中的插入操作
思路:遍历至空节点插入即可
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) {
root = new TreeNode(val);
return root;
}
insert(root, val);
return root;
}
void insert(TreeNode* node, int val) {
// 当前节点大于插入值,向左遍历
if(node->val > val) {
if(node->left) insertIntoBST(node->left, val);
else node->left = new TreeNode(val);
}
// 当前节点小于插入值,向右遍历
if(node->val < val) {
if(node->right) insertIntoBST(node->right, val);
else node->right = new TreeNode(val);
}
return ;
}
};
450.删除二叉搜索树中的节点
难点:当待删除的节点的左右子树都不为空时:
将当前节点的左子树挂载到右子树的最左边;
然后将当前指针指向当前节点的右子树。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
// 1.如果根节点为空,或者没有找到key,直接返回nullptr
if(root == nullptr) return nullptr;
// 如果找到key
if(root->val == key) {
// 2.如果待删除节点的左右孩子都为空,直接删除节点返回nullptr
if(!root->left && !root->right) {
delete root;
return nullptr;
}
// 3.如果待删除节点左孩子不为空,右孩子为空
else if(root->left && !root->right) {
TreeNode* tem = root->left;
delete root;
return tem;
}
// 4.如果待删除节点的右孩子不空,左孩子为空
else if(!root->left && root->right) {
TreeNode* tem = root->right;
delete root;
return tem;
}
// 5.如果待删除节点的左右孩子都不为空
else {
TreeNode* tem = root;
TreeNode* cur = root->right;
while(cur->left) cur = cur->left;
cur->left = root->left;
root = root->right;
delete tem;
return root;
}
}
if(root->val > key) {
root->left = deleteNode(root->left, key);
}
if(root->val < key) {
root->right = deleteNode(root->right, key);
}
return root;
}
};
标签:right,TreeNode,val,root,二叉,搜索,return,树中,left
From: https://www.cnblogs.com/cscpp/p/18228251