剑指Offer19

剑指Offer第十九天

回溯算法(中等)

在这里插入图片描述

题1:求1+2+…+n

1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
在这里插入图片描述

参考题解:https://leetcode-cn.com/problems/qiu-12n-lcof/solution/mian-shi-ti-64-qiu-1-2-nluo-ji-fu-duan-lu-qing-xi-/

虽然我觉得这种题没啥价值,但是确实不会,也学到了,学到了就有价值。。

class Solution {
    public int sumNums(int n) {
        //递归,短路效应
        int sum = n;
        boolean flag = n > 0 && (sum += sumNums(n - 1)) > 0;
        return sum;
    }
}

在这里插入图片描述

题2:二叉搜索树的最近公共祖先1

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
在这里插入图片描述

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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){
            return lowestCommonAncestor(root.left, p, q);
        }
        if(root.val < p.val && root.val < q.val){
            return lowestCommonAncestor(root.right, p, q);
        }
        return root;
    }
}

在这里插入图片描述

题3:二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

在这里插入图片描述

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
     //三种情况:
     //1、p q 一个在左子树 一个在右子树 那么当前节点即是最近公共祖先
     //2、p q 都在左子树 
     //3、p q 都在右子树
        if(root == null){
            return null;
        }
        if(root == p || root == q){
            return root;
        }
        //先找出p,q的大体位置,如果都在左边,必然有root.left是p,q的公共祖先,所以必然有返回值,且右边返回值必然是null
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        //如果都在右边,必然有root.right是p,q的公共祖先,所以必然有返回值,且左边返回值必然是null
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        //如果异侧,那么左右两边都会有返回值,因为root == p || root == q肯定会满足一个。。
        if(left != null && right != null){
            return root;
        }
        if(left != null){
            //p,q都在左子树
            return left;
        }
        if(right != null){
            //p,q都在右子树
            return right;
        }
        return null;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值