LeetCode 235. 二叉搜索树的最近公共祖先
由于二叉搜索树是有序的,如果当前节点的值在[p,q]之间,则从上至下遍历第一次遇到的节点便是最近的公共祖先,因为此后不管是向左遍历还是向右遍历,都会找不到另一个节点了(往左走都是小于当前节点的值不会找到q节点,往右走全是大于当前节点的值不会找到p节点了)。代码如下:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
return root;
}
}
LeetCode 701.二叉搜索树中的插入操作
本题一时没想到怎么处理新节点返回值,也不确定终止条件怎么定义,究竟是root==null 还是root.left == null && root.right == null ,用自己写的代码交了几次还是没过当root为空时。看了题解之后恍然大悟,可以通过返回值来将新增节点返回给上一层。可能许久没有写二叉树插入节点相关的代码,有些生疏和不知所措了。通过的代码如下:
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) {
TreeNode cur = new TreeNode(val);
return cur;
}
if(root.val > val) root.left = insertIntoBST(root.left, val);
if(root.val < val) root.right = insertIntoBST(root.right, val);
return root;
}
}
LeetCode 450.删除二叉搜索树中的节点
删除节点需要考虑一下情况:
1.没有找到key对应的节点,遍历到空节点直接返回;
2.找到key对应的节点:1)如果该节点的左右孩子均为null,则直接删除返回null即可;2)如果左孩子为空右孩子不为空,则将该节点的右孩子直接填补;3)如果左孩子不为空,右孩子为空,则将该节点的左孩子直接填补;4)如果左右孩子均不为空,需要先遍历右子树,找到其最左边的节点,并将左子树接到最左边节点的左孩子上,返回该节点的右孩子作为当前根节点。
其中1)和3)可以直接归为一种情况,直接返回左孩子即可;
代码如下:
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;
if(root.val == key){
// 删除操作
if(root.left == null && root.right != null) return root.right;
if(root.left != null && root.right != null) {
TreeNode leftest = transerval(root.right);
leftest.left = root.left;
return root.right;
}
return root.left;
}
if(root.val > key) root.left = deleteNode(root.left, key);
if(root.val < key) root.right = deleteNode(root.right, key);
return root;
}
public TreeNode transerval(TreeNode node) {
if(node.left == null) return node;
return transerval(node.left);
}
}