235.二叉搜索树的最近公共祖先
二叉搜索树更简单一点,直接通过当前节点跟寻找节点比较就好了。
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
701.二叉搜索树中的插入操作
首先,这道题不需要操作二叉树,所以一开始千万不要想复杂。
- 终止条件,当节点为空的时候直接创建需要插入的节点并返回就好了。
- 逻辑处理:其实我们只需要一直深入遍历,插入值比当前节点值小就向左深入,大就向右深入。
- 这里有个要注意的就是,我们需要对应子节点接住返回的节点。
TreeNode preNode = null;
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.删除二叉搜索树中的节点
有以下五种情况:
-
第一种情况:没找到删除的节点,遍历到空节点直接返回了
-
找到删除的节点
- 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
- 第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
- 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
- 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
第五种情况有点难以理解,看下面动画:
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return root;
if (root.val == key) {
if (root.left == null && root.right == null) {
return null;
} else 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;
}
总结
有点难哎。