235. 二叉搜索树的最近公共祖先
题目链接:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
思路:递归法,找到值在p,q两点之间的节点,理由是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);
return left;
}
if(root.val < p.val && root.val < q.val){
TreeNode right = lowestCommonAncestor(root.right,p,q);
return right;
}
return root;
}
}
701.二叉搜索树中的插入操作
题目链接:701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
思路:不考虑深度差的话,直接插入到叶子节点
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode newroot = root;
TreeNode pre = root;
while(root != null){
pre = root;
if(root.val > val){
root = root.left;
}else if(root.val < val){
root = root.right;
}
}
if(pre.val > val){
pre.left = new TreeNode(val);
}else{
pre.right = new TreeNode(val);
}
return newroot;
}
}
450.删除二叉搜索树中的节点
题目链接:450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
思路:删除节点子不为空,右孩子接位,右孩子移到右孩子的最左下角
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;
if(root.val == key){
if(root.left == null){
return root.right;
}else if(root.right == null){
return root.left;
}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;
}
}