NC102 在二叉树中找到两个节点的最近公共祖先
题目链接
1、解题思路
- 递归。
- 如果当前节点为空,说明到底了,直接返回null,
- 如果当前节点的值等于v1或者v2直接把当前节点返回。
- 递归找左子树或者右子树,
- 如果左右各找到一个,返回当前节点
- 如果左右有个不为空,返回不为空的那个
- 如果左右都找不到,返回空
2、代码
import java.util.*;
public class Solution {
private TreeNode lowestCommonAncestorHelper(TreeNode node,int v1,int v2){
if(node == null){
return null;
}else if(node.val == v1 || node.val == v2){
return node;
}else{
TreeNode left = lowestCommonAncestorHelper(node.left,v1,v2);
TreeNode right = lowestCommonAncestorHelper(node.right,v1,v2);
if(left != null && right != null){
return node;
}else if(left != null){
return left;
}else if(right != null){
return right;
}else{
return null;
}
}
}
public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
return lowestCommonAncestorHelper(root,o1,o2).val;
}
}
复制代码
NC103 反转字符串
题目链接
1、解题思路
2、代码
import java.util.*;
public class Solution {
public String solve (String str) {
char[] arr = str.toCharArray();
int l = 0;
int r = arr.length - 1;
while(l < r){
char c = arr[l];
arr[l] = arr[r];
arr[r] = c;
l++;
r--;
}
return new String(arr);
}
}
复制代码
NC38 螺旋矩阵
题目链接
1、解题思路
2、代码
import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(matrix.length == 0 || matrix[0].length == 0){
return list;
}
int topR = 0;
int topC = 0;
int botR = matrix.length - 1;
int botC = matrix[0].length - 1;
while(true){
if(topR > botR){
break;
}
if(topC > botC){
break;
}
for(int i = topC;i <= botC;i++){
list.add(matrix[topR][i]);
}
for(int i = topR + 1;i <= botR;i++){
list.add(matrix[i][botC]);
}
if(botR != topR){
for(int i = botC - 1;i >= topC;i--){
list.add(matrix[botR][i]);
}
}
if(botC != topC){
for(int i = botR - 1;i > topR;i--){
list.add(matrix[i][topC]);
}
}
topC++;
topR++;
botR--;
botC--;
}
return list;
}
}
复制代码