Day22题目
LeetCode235.二叉搜索树的最近公共父节点
核心思想:最近的公共父节点一定是分别在这个父节点的两侧。同时因为是二叉搜索树,所以只要找到第一个值的大小在所给两个节点中间的就可以了
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 如果p在左子树,q在右子树,那么这个节点就是最近的,只需要判断root的值在p 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;
}
}
LeetCode701.二叉搜索树中的插入操作
核心思想:遍历搜索树,如果比它大就想左遍历,小就向右遍历,知道得到空,把节点放上去。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
// res 是最后的返回值
TreeNode res = root;
// 记录上一个遍历的节点
TreeNode pre = null;
while(true){
if(root == null){
// 如果root 为null 并且pre是null的话,那么说明原来就是空的。
if(pre ==null){
return new TreeNode(val);
// 已经遍历到了null,根据val的大小插入到pre的左侧或者右侧
}else if(pre.val > val){
pre.left = new TreeNode(val);
}else{
pre.right = new TreeNode(val);
}
return res;
}
// 这里遍历寻找合适的位置进行插入
if(root.val < val){
// 小了向右
pre = root;
root =root.right;
}else
if(root.val > val){
// 大了向左
pre = root;
root = root.left;
}
}
}
}
LeetCode405.删除二叉搜索树的节点
核心思想:首先遍历找到要删除的节点,删除有多种情况,需要一一处理
- 被删除的节点没有子节点:直接删除
- 被删除的节点只有一个子节点:将子节点替换自己
- 被删除的节点有两个子节点:将左子树放到右子树的左下角,然后用右子树替换自己
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return null;
if(root.val < key ){
// 寻找被删除的节点
root.right = deleteNode(root.right,key);
}else if(root.val > key) {
root.left = deleteNode(root.left,key);
}else{
// 找到了被删除的节点,开始进行删除
// 1. 左右都没有,直接删掉
if(root.left == null && root.right == null){
return null;
}
// 2. 左右中只有一个有
if(root.right == null){
return root.left;
}
if(root.left == null){
return root.right;
}
// 3. 左右都有
// 首先得到右节点的左下角
TreeNode temp = root.right;
while(temp.left !=null){
temp =temp.left;
}
// 把左子树移动到右子树的左下角
temp.left = root.left;
// 返回右子树
root = root.right;
return root;
}
return root;
}
}
2028



被折叠的 条评论
为什么被折叠?



