day22 打卡235. 二叉搜索树的最近公共祖先 701.二叉搜索树中的插入操作 450.删除二叉搜索树中的节点
235. 二叉搜索树的最近公共祖先
1.递归法。利用二叉搜素树中间节点肯定大于左子树,小于右子树的特征。
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) {
// 向左子树搜索
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;
}
}
2.迭代法
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
if (root.val > p.val && root.val > q.val) {
root = root.left;
} else if (root.val < p.val && root.val < q.val) {
root = root.right;
} else {
break;
}
}
return root;
}
}
701.二叉搜索树中的插入操作
1.迭代法
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode add = new TreeNode(val);
if (root == null) return add;
TreeNode cur = root;
TreeNode pre = null;
while (true) {
if (cur == null) break;
pre = cur;
if (cur.val > val) {
cur = cur.left;
} else if (cur.val < val) {
cur = cur.right;
}
}
if (pre.val > val) {
pre.left = add;
} else if (pre.val < val) {
pre.right = add;
}
return root;
}
}
2.递归法
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);;
if (root.val > val) {
root.left = insertIntoBST(root.left, val);
}
if (root.val < val) {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}
450.删除二叉搜索树中的节点
1.递归法
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;
root = root.right;
return root;
}
}
if (root.val > key) root.left = deleteNode(root.left, key);
if (root.val < key) root.right = deleteNode(root.right, key);
return root;
}
}