235. 二叉搜索树的最近公共祖先(二刷用迭代法)
解决这道题的关键是理解二叉搜索树的性质。
二叉搜索树的遍历方向已经固定了。(大的往右,小的往左)
关键一点:从上向下遍历,第一次遇到cur节点是数值再[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);
// 找到最早的公共节点就返回
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. 二叉搜索树中的插入操作 (二刷用迭代法)
这里利用二叉搜索树的特性,直接递归,并不需要修改树的结构,遇到合适的空节点直接插入就可以。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) {
root = new TreeNode(val);
return root;
}
if(root.val > val){
root.left = insertIntoBST(root.left,val);
}else if(root.val < val){
root.right = insertIntoBST(root.right,val);
}
return root;
}
}
450. 删除二叉搜索树中的节点 (二刷用迭代法)
链接: 删除二叉搜索树中的节点
这道题需要分情况讨论,最难的情况为要删除的节点左右子树都不为空。
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){
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 > key) root.left = deleteNode(root.left, key);
// 将新构造的树返回到右子树下
if(root.val < key) root.right = deleteNode(root.right, key);
return root;
}
}