代码随想录算法训练营第22天|235.二叉搜索树的最近公共祖先、701.二叉搜索树中的插入操作 、450.删除二叉搜索树中的节点
一. 二叉树相关算法题
235.二叉搜索树的最近公共祖先
思路
- 本题可以利用二叉搜索树的有序性,自顶向下查找在[p,q]]
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){
TreeNode left = lowestCommonAncestor(root.left, p, q);
if (left != null) {
return left;
}
}
if (root.val<p.val && root.val <q.val){
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (right != null) {
return right;
}
}
return root;
}
}
701.二叉搜索树中的插入操作
递归法
思路
- 以根节点为基础递归构建左右子树,如果节点为空那么说明找val的位置了
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
TreeNode node = new TreeNode(val);
return node;
}
if (root.val>val) root.left = insertIntoBST(root.left,val) ;
if (root.val<val) root.right = insertIntoBST(root.right,val);
return root;
}
}
450.删除二叉搜索树中的节点
递归(中序遍历)
思路
- 根据二叉搜索树的特性判断向左或者向右搜索目标节点
- 如果搜索到返回下一节点,最后递归返回根节点
- 一共有五种情况
- 没有搜索到节点直接返回空
- 搜索到节点左右子树都为空直接删除返回null
- 搜索的节点只有一个左子树 返回左子树
- 搜索的节点只有一个右子树 返回右子树
- 左右子树都不为空:将右子树根节点覆盖当前节点左子树指向右子树左下角节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return null;
if(root.val == key) {
if (root.left == null && root.right == null){
root = null;
return root;
}
else if (root.left == null && root.right != null){
return root.right;
}
else if (root.left != null && root.right == null) {
return root.left;
}
else {
TreeNode node = root.right;
while (node.left != null){
node = node.left;
}
node.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;
}
}