栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

8月算法训练------第九天(搜索与回溯)解题报告

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

8月算法训练------第九天(搜索与回溯)解题报告

8月算法训练------第九天(搜索与回溯)解题报告

题目类型:搜索与回溯
题目难度:中等

第一题、剑指 Offer 64. 求1+2+…+n
  1. 题目链接:剑指 Offer 64. 求1+2+…+n
  2. 思路分析:
    题目中说不能用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
    但我们知道,这一题如果运用for循环将会十分简单,所以我们采用与循环思路类似的递归来求解,递归和循环在一定程度上是可以相互转化的。
  3. 代码:
class Solution {
    public int sumNums(int n) {
        return sum(n);
    }
    public int sum(int n){
        if(n == 1){
            return 1;
        }
        return n + sum(n-1);
    }
}
第二题、剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
  1. 题目链接:剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
  2. 思路分析:
    因为本题中的树是二叉搜索树,所以对这棵树的遍历还是比较简单的,将二叉树的遍历过的节点装进一个List集合中,代表要求节点所经过的根节点。
    得到这两个LIst集合后,二叉树的公共祖先就在其中,只需要遍历这两个节点,找到最后一个相等的公共节点,就是最近的公共祖先。
  3. 代码:
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        List path_p = pathWay(root, p);
        List path_q = pathWay(root, q);
        TreeNode anc = null;
        for(int i = 0; i < path_p.size() && i < path_q.size(); i++){
            if(path_p.get(i) == path_q.get(i)){
                anc = path_p.get(i);
            }else{
                break;
            }
            
        }
        return anc;
    }
    public List pathWay(TreeNode root, TreeNode target){
        List path = new ArrayList();
        TreeNode node = root;
        while(node != target){
            path.add(node);
            if(node.val < target.val){
                node = node.right;
            }else{
                node = node.left;
            }
        }
        path.add(node);
        return path;
    }
}
第三题、剑指 Offer 68 - II. 二叉树的最近公共祖先
  1. 题目链接:剑指 Offer 68 - II. 二叉树的最近公共祖先
  2. 思路分析:
    这一题相对于上一题还是有很多不一样的,
    通过分析,得到这一题的结果有以下几种情况:
  • 节点p和q分别在公共祖先root的左右,即root.left != null且root.right != null
  • 公共祖先root为p,节点q在root的左右子树中,即root.left == null或root.right == null时;
  • 公共祖先root为q,节点p在root的左右子树中,代码表现与上一种情况一样。
  1. 代码:
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) return right;
        if(right == null) return left;
        return root;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1038044.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号