代码随想录day19 Java版

236. 二叉树的最近公共祖先

由于需要从下向上回溯,选用后序遍历

当找到这两个节点或者空时返回该节点,先进行左右递归,然后处理该节点:都找到时才返回该节点,因为是后序所以肯定返回最下层也就是最近的公共祖先,左右之一找不到时就说明,最近公共祖先是p和q中的一个,就返回另一边。都找不到就返回null。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p,q);
        TreeNode right= lowestCommonAncestor(root.right,p,q);
        if (left == null && right == null) return null;
        if (left == null) return right;
        if (right== null) return left;
        return root;
    }
}

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

在上一题的基础上加了二叉搜索树的条件,相当于二叉树变成了有序数组,因为公共祖先节点一定在p和q中间,所以大了就往左边找,小了就往右边找。

class Solution {
    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.二叉搜索树中的插入操作

在二叉搜索树中根本不用写遍历,直接根据值左右查找

当节点为空说明找到了末端,将新节点返回给上层递归的节点

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 (key == root.val) {
            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;
                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;
    }
}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值