题目链接:235. 二叉搜索树的最近公共祖先
看完代码随想录之后的想法:
还是不好理解的,今后继续做;
题目链接:701.二叉搜索树中的插入操作
题目链接/文章讲解:
视频讲解:
看完代码随想录之后的想法:
我们插入入的节点都在叶子节点,因此,我们的终止条件是在root == null 的时候插入新节点同时终止递归;
我们的返回值是TreeNode ,参数是TreeNode, val;
单次逻辑是
如果val < root.val 我们左递归;
如果val > root.val 我们右递归;
我们不需要处理中间节点;
class Solution {
TreeNode insert(TreeNode root, int val) {
if(root == null) {
TreeNode node = new TreeNode(val);
return node;
}
if(val < root.val)
root.left = insert(root.left, val);
else
root.right = insert(root.right, val);
return root;
}
public TreeNode insertIntoBST(TreeNode root, int val) {
return insert(root, val);
}
}
题目链接:450.删除二叉搜索树中的节点
题目链接/文章讲解:
视频讲解:
看完代码随想录之后的想法:
我们要分析一下;我们删除节点右5种情况;
第一种:没有找到需要删除的节点;
第二种:需要删除的节点左右节点为空;
第三种:需要删除的节点左节点为空,右节点不为空
第四种:需要删除的节点左节点不为空,右节点为空;
第五种:需要删除的节点左右节点都不为空;
class Solution {
TreeNode delete(TreeNode root, int val) {
if(root == null) return null;
if(root.val == val) {
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 > val)
root.left = delete(root.left, val);
if(root.val < val)
root.right = delete(root.right, val);
return root;
}
public TreeNode deleteNode(TreeNode root, int key) {
return delete(root, key);
}
}