题目类型:搜索与回溯
题目难度:中等
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);
}
}
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;
}
}
root.left != null
且root.right != null
root.left == null
或root.right == null
时;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;
}
}