Day 20 二叉树part07

235. 二叉搜索树的最近公共祖先

总体上思想与236. 二叉树的最近公共祖先思路是一致的,都是去搜索p,q的位置。这个大框架是最难理解的部分,具体可以再去看看236的题解。这道题在其基础上利用了搜索树的性质,当根节点的val大于pq两者时,就去左子树找结果即可;反之则去右子树中查找。当p,q一个比root大另一个小,说明p,q位于root的两个子树中,其最近公共祖先一定是root。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        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. 二叉搜索树中的插入操作

还是要更好的去理解递归。具体看注释

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. 删除二叉搜索树中的节点

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;
            if(root.right == null) //同理
                return root.left;
            //左右子树都不为空
            TreeNode leftMax = root.left; //找到左子树的最大值
            while(leftMax.right != null){
                leftMax = leftMax.right;
            }
            root.left = deleteNode(root.left, leftMax.val); //从左子树中删除leftMax
            leftMax.left = root.left;
            leftMax.right = root.right;
            return leftMax; //将左子树的最大值作为新的根节点
        }
        if(root.val > key) //要删除的节点位于左子树
            root.left = deleteNode(root.left, key);
        if(root.val < key) //位于右子树
            root.right = deleteNode(root.right, key);
        return root;
    }
}
posted @ 2024-07-22 14:56  12点不睡觉还想干啥?  阅读(23)  评论(0)    收藏  举报