第十九天——搜索与回溯算法
第一题:剑指 Offer 64. 求1+2+…+n
问题描述
思路
代码
class Solution {
public int sumNums(int n) {
int sum = n;
boolean flag = n > 0 && (sum += sumNums(n-1)) > 0;
return sum;
}
}
第二题:剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
问题描述
思路
代码
/**
* 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.right,p,q);
if(root.val > p.val && root.val > q.val)
return lowestCommonAncestor(root.left,p,q);
return root;
}
}
第三题:剑指 Offer 68 - II. 二叉树的最近公共祖先
问题描述
思路
代码
/**
* 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 == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
// p q 一个在左,一个在右
return root;
}
if (left != null) {
// p q 都在左子树
return left;
}
if (right != null) {
// p q 都在右子树
return right;
}
return null;
}
}