剑指offer-day19
求1+2+…+n
感觉本质上是一道脑筋急转弯题目,因为迭代和递归的方式都被锁死了,只能另辟蹊径完成,答案用的是逻辑运算符的短路,也见到有人用异常的,我没有想出来,就以答案为标准吧。
1 2 3 4 5 6 7 8 9
| class Solution { int res = 0; public int sumNums(int n) { boolean x = n > 1 && sumNums(n-1) > 0; res += n; return res; } }
|
二叉搜索树的最近公共祖先
自己想出来了递归,答案给的最优解是迭代,但是实际实验过发现两者并没有差别,那就放自己的答案吧。
因为是二叉搜索树,可以利用搜索树的特性,判断两个节点是否在一侧,在哪一侧则往哪边遍历,否则就返回当前的根节点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val > p.val && root.val > q.val){ return lowestCommonAncestor(root.left,p,q); } else if(root.val < p.val && root.val < q.val){ return lowestCommonAncestor(root.right,p,q); } return root; } }
|
二叉树的最近祖先
相比上题少了一个搜索树的条件,显然变难了,自己写的是递归+遍历,有很高的时间复杂度,最优解只使用了递归。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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; } }
|