235. 二叉搜索树的最近公共祖先
题目链接
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
题目描述
相较于前一天的题不同,昨天的题是二叉树,这次重点强调了是二叉搜索树
思路
1、迭代法
因为二叉搜索树本身就是有序的,所以不需要去管前中后序三种遍历方法,直接判断大小即可整体思路就是判断 p,q 节点的值与根节点的大小,如果同时小于根节点,那公共祖先就在根节点的左子树 如果同时大于根节点,那么公共祖先就在根节点的右子树, 如果根节点的值介于两个节点之间,说明根节点就是祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//迭代法
if(root==null) return null;
while (root!=null){
if(root.val>p.val&&root.val>q.val){
root = root.left;
}else if(root.val<p.val&&root.val<q.val){
root = root.right;
}else {
return root;
}
}
return null;
}
}
2、递归法
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) return null;
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;
}
}
701.二叉搜索树中的插入操作
题目链接
https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/
题目描述
思路
public TreeNode insertIntoBST(TreeNode root, int val) {
//递归方法
//如果当前节点为空,说明此位置就是新节点将要插入的位置
if(root==null) return new TreeNode(val);
//如果根节点的值大于目标值,则向根节点的左侧递归
//再判断如果根节点的左孩子不为空,继续递归,为空,就插入这里
if(root.val>val){
if(root.left!=null){
insertIntoBST(root.left,val);
}else {
root.left = new TreeNode(val);
}
}
//根节点大于目标值的思路类似上边
if(root.val<val){
if(root.right!=null){
insertIntoBST(root.right,val);
}else {
root.right = new TreeNode(val);
}
}
return root;
}
450.删除二叉搜索树中的节点
题目链接
https://leetcode.cn/problems/delete-node-in-a-bst/description/
题目描述
思路
第五种情况的处理逻辑:
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
//本题可以分为五种情况
//1、没有找到想要删除的元素
//2、找到了想要删除的元素,且删除的元素是叶子节点,即左右孩子均为空
//3、找到了想要删除的元素,且删除的元素左孩子不为空右孩子为空
//4、找到了想要删除的元素,且删除的元素左孩子为空右孩子不为空
//5、找到了想要删除的元素,且删除的元素左右孩子均不为空
if(root==null) return root;
if(root.val==key){
if(root.left==null&&root.right==null){
return null;
}else if(root.left!=null&&root.right==null){
return root.left;
}else if(root.left==null&&root.right!=null){
return root.right;
}else {
TreeNode cur = root.right;
while (cur.left!=null){
cur = cur.left;
}
cur.left=root.left;
//此时将删除元素的左孩子放在了删除元素右孩子的最小的左孩子的位置
//就相当于当前删除元素左孩子为空,右孩子不为空
return root.right;
}
}
if(root.val>key){
//返回的节点应该用当前节点的左孩子接住
root.left = deleteNode(root.left,key);
}
if(root.val<key){
//返回的节点应该用当前节点的右孩子接住
root.right = deleteNode(root.right,key);
}
return root;
}
}