二叉树8|235. 二叉搜索树的最近公共祖先|701.二叉搜索树中的插入操作|450.删除二叉搜索树中的节点
一、235. 二叉搜索树的最近公共祖先
题目连接:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
- 思路:二叉搜索树的中序遍历递增,因为是有序树,所有 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点> p &&中节小于q 或者 中节点 > q && 中节点 < p。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
if(root == null) return root;
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.二叉搜索树中的插入操作
题目连接:701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
- 利用二叉搜索树的性质,递归找到插入的位置。终止条件就是找到遍历的节点为null的时候,就是要插入节点的位置了,并把插入的节点返回。 添加的节点返回给上一层,就完成了父子节点的赋值操作了 。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null){
TreeNode node = new TreeNode(val);
return node;
}
if(val < root.val) root.left = insertIntoBST(root.left, val);
if(val > root.val) root.right = insertIntoBST(root.right, val);
return root;
}
}
三、450.删除二叉搜索树中的节点
题目连接:450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
-
有五种情况
第一种情况:没找到删除的节点,遍历到空节点直接返回了
- 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
- 第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
- 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
- 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
root = delete(root,key);
return root;
}
public TreeNode delete(TreeNode root, int key){
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.right;
}else if(root.left != null && root.right == null){
return root.left;
}else {
TreeNode cur = root.right;
while(cur.left != null){
cur = cur.left;
}
cur.left = root.left;
root = root.right;
return root;
}
}
if(root.val < key) root.right = delete(root.right, key);
if(root.val > key) root.left = delete(root.left, key);
return root;
}
}