feat: 螺旋矩阵、公共祖先
This commit is contained in:
parent
d1b30aa532
commit
d3eca96b35
|
|
@ -0,0 +1,37 @@
|
|||
package leecode.java;
|
||||
|
||||
import leecode.tree.TreeNode;
|
||||
|
||||
/**
|
||||
* @author Wen
|
||||
* @date 2025/6/19 20:48
|
||||
*/
|
||||
public class No236 {
|
||||
|
||||
private TreeNode result = null;
|
||||
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
||||
dfs(root, p, q);
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean dfs(TreeNode root, TreeNode p, TreeNode q) {
|
||||
if (root == null) {
|
||||
return false;
|
||||
}
|
||||
boolean lson = dfs(root.left, p, q);
|
||||
boolean rson = dfs(root.right, p, q);
|
||||
// 自己是公共祖先
|
||||
if (root.val == p.val || root.val == q.val) {
|
||||
if (lson || rson) {
|
||||
result = root;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// 一般情况下的公共祖先,分别在该节点的左右子树
|
||||
if (lson && rson) {
|
||||
result = root;
|
||||
return true;
|
||||
}
|
||||
return lson || rson;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package leecode.java;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Wen
|
||||
* @date 2025/6/19 13:18
|
||||
*/
|
||||
public class No54 {
|
||||
|
||||
public List<Integer> spiralOrder(int[][] matrix) {
|
||||
String a = "";
|
||||
String.valueOf(a.charAt(1));
|
||||
List<Integer> result = new ArrayList<>();
|
||||
dfs(result, matrix, 0, 0, matrix.length, matrix[0].length);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public void dfs(List<Integer> result, int[][] matrix, int x, int y, int height, int width) {
|
||||
if (height <= 0 || width <= 0) {
|
||||
return;
|
||||
}
|
||||
// 单横边情况处理
|
||||
if (height == 1) {
|
||||
for (int i = x; i < x + width; i++) {
|
||||
result.add(matrix[y][i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 单竖边情况处理
|
||||
if (width == 1) {
|
||||
for (int i = y; i < y + height; i++) {
|
||||
result.add(matrix[i][x]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (int i = x; i < x + width - 1; i++) {
|
||||
result.add(matrix[y][i]);
|
||||
}
|
||||
for (int i = y; i < y + height - 1; i++) {
|
||||
result.add(matrix[i][x + width - 1]);
|
||||
}
|
||||
for (int i = x + width - 1; i > x; i--) {
|
||||
result.add(matrix[y + height - 1][i]);
|
||||
}
|
||||
for (int i = y + height - 1; i > y; i--) {
|
||||
result.add(matrix[i][x]);
|
||||
}
|
||||
dfs(result, matrix, x + 1, y + 1, height - 2, width - 2);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
No54 no54 = new No54();
|
||||
int[][] matrix = {
|
||||
{1, 2, 3},
|
||||
{4, 5, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
System.out.println(no54.spiralOrder(matrix));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue