剑指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;
}
}