这是我参与8月更文挑战的第13天,活动详情查看:8月更文挑战
剑指 Offer 28. 对称的二叉树
题目
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1 / 2 2 / \ / 3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1 / 2 2 \ 3 3
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
限制:
0 <= 节点个数 <= 1000
方法一
递归:首先判断当前两个结点是否相等,不相等直接返回false;相等,继续往下递归判断
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return dfs(root.left, root.right);
}
boolean dfs(TreeNode l, TreeNode r) {
if (l == null && r == null) return true;
if (l == null && r != null || r == null && l != null || l.val != r.val) return false;
return dfs(l.right, r.left) && dfs(l.left, r.right);
}
}
时间复杂度: O(n)
空间复杂度: O(n)
剑指 Offer 29. 顺时针打印矩阵
题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 1000 <= matrix[i].length <= 100
方法一
模拟:按照题意模拟一遍即可,外层while控制走的步数,内层4个while分别控制往左,往下,往右,往上四个方法;
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0) return new int[0];
int n = matrix.length, m = matrix[0].length;
boolean[][] st = new boolean[n][m];
int[] res = new int[n * m];
int i = 0, j = 0, cnt = 0;
while (cnt < n * m) {
while(j < m && !st[i][j]) {
st[i][j] = true;
res[cnt ++] = matrix[i][j];
j ++;
}
i ++; j --;
while(i < n && !st[i][j]) {
st[i][j] = true;
res[cnt ++] = matrix[i][j];
i ++;
}
i --; j --;
while(j >= 0 && !st[i][j]) {
st[i][j] = true;
res[cnt ++] = matrix[i][j];
j --;
}
i --; j ++;
while(i >= 0 && !st[i][j]) {
st[i][j] = true;
res[cnt ++] = matrix[i][j];
i --;
}
i ++; j ++;
}
return res;
}
}
时间复杂度: O(n*n)
空间复杂度: O(n*n)