8月算法训练------第九天(搜索与回溯)解题报告
题目类型:搜索与回溯
题目难度:中等
第一题、剑指 Offer 64. 求1+2+…+n
- 题目链接:剑指 Offer 64. 求1+2+…+n
- 思路分析:
题目中说不能用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
但我们知道,这一题如果运用for循环将会十分简单,所以我们采用与循环思路类似的递归来求解,递归和循环在一定程度上是可以相互转化的。 - 代码:
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. 二叉搜索树的最近公共祖先
- 题目链接:剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
- 思路分析:
因为本题中的树是二叉搜索树,所以对这棵树的遍历还是比较简单的,将二叉树的遍历过的节点装进一个List集合中,代表要求节点所经过的根节点。
得到这两个LIst集合后,二叉树的公共祖先就在其中,只需要遍历这两个节点,找到最后一个相等的公共节点,就是最近的公共祖先。 - 代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> path_p = pathWay(root, p);
List<TreeNode> 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<TreeNode> pathWay(TreeNode root, TreeNode target){
List<TreeNode> 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. 二叉树的最近公共祖先
- 题目链接:剑指 Offer 68 - II. 二叉树的最近公共祖先
- 思路分析:
这一题相对于上一题还是有很多不一样的,
通过分析,得到这一题的结果有以下几种情况:
- 节点p和q分别在公共祖先root的左右,即
root.left != null
且root.right != null
- 公共祖先root为p,节点q在root的左右子树中,即
root.left == null
或root.right == null
时; - 公共祖先root为q,节点p在root的左右子树中,代码表现与上一种情况一样。
- 代码:
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;
}
}