3道题目
235. 二叉搜索树的最近公共祖先
701. 二叉搜索树中的插入操作
450. 删除二叉搜索树中的节点
解题理解
235
这道题让我想起昨天的236题,不同的是这道题是二叉搜索树,所以一定要利用左<中<右的特性。
236主要是回溯过程中判断有没有找到目标结点,没有就一个节点一个节点的把null返回上去,那在这道题里,可以从根节点直接确定找目标结点的方向,即给定的两个节点若都大于根节点,说明目标结点在右子树里;若都小于根节点,则在左子树里;若既不满足同时大于又不满足同时小于,说明当前节点在两节点中间,则当前节点就是最近公共祖先。
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);
else if(root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q);
else return root;
}
};
701
这道题我一直有种情况考虑不清楚,即要插入的节点应该出现在树中怎么办,结果就是各种边界各种判断想了一堆也做不出来。
不过题目中有说任意结果都可以,所以题解中的写法也只是让插入节点永远插入到叶子节点的位置上。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr){
TreeNode* node = new TreeNode(val);
return node;
}
if(val > root->val) root->right = insertIntoBST(root->right, val);
if(val < root->val) root->left = insertIntoBST(root->left, val);
return root;
}
};
450
删除节点的逻辑有些难,我只能想到左右子树的递归,当找到需要被删除的结点时,就又陷入了理不清的边界条件和判断里。
正确思路是,找到待删除结点(target)后,先判断左子树是否为空,空就返回右子树;若左子树不为空就判断右子树,右子树为空就返回左子树;若孩子都不为空,就去找右子树的最左结点(new);找到后将target的整个左子树都放到new的左子树位置上。最后将new作为新的根节点返回上去。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr) return nullptr;
if(root->val == key){
if(root->left == nullptr) return root->right;
else if(root->right == nullptr) return root->left;
else{
TreeNode* node = root->right;
while(node->left != nullptr){
node = node->left;
}
node->left = root->left;
TreeNode* 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;
}
};
感觉这道题的写法对搜索树的性质掌握的更深了,之前的理解只局限于当前节点与左右孩子的关系,没有注意到整个左子树都是小于右子树任一结点的。也正是这个特性,才可以递归接触这道题。