117. 填充每个节点的下一个右侧节点指针 II
public Node connect(Node root) {
if (root == null)
return root;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int levelCount = queue.size();
Node pre = null;
for (int i = 0; i < levelCount; i++) {
Node node = queue.poll();
if (pre != null) {
pre.next = node;
}
pre = node;
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
}
return root;
}
572. 另一个树的子树
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null && t == null)
return true;
if (s == null || t == null) return false;
if (isEqual(s, t)) {
return true;
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
public boolean isEqual(TreeNode l, TreeNode r) {
if (l == null && r == null) return true;
if (l == null || r == null) return false;
if (l.val == r.val) return isEqual(l.left, r.left) && isEqual(l.right, r.right);
return false;
}
59. 螺旋矩阵 II
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int t = 0, b = n - 1, l = 0, r = n - 1;
int i = 1;
while(i <= n * n) {
for(int j = l; j <= r; j++)
ans[t][j] = i++;
t++;
for(int j = t; j <= b; j++)
ans[j][r] = i++;
r--;
for(int j = r; j >= l; j--)
ans[b][j] = i++;
b--;
for(int j = b; j >= t; j--)
ans[j][l] = i++;
l++;
}
return ans;
}
60.排列序列
本来用回溯结果超时 还是得看题解找规律
public String getPermutation(int n, int k) {
List<Integer> ans = new ArrayList<>();
for (int i = 1; i <= n; i++) {
ans.add(i);
}
int[] fact = new int[n];
fact[0] = 1;
for (int i = 1; i < n; i++) {
fact[i] = i * fact[i - 1];
}
k = k - 1;
StringBuilder sb = new StringBuilder();
for (int i = n; i > 0; i--) {
int index = k / fact[i - 1];
k = k % fact[i - 1];
sb.append(ans.get(index));
ans.remove(index);
}
return sb.toString();
}
61.旋转链表
感觉双指针其实更好理解
public ListNode rotateRight(ListNode head, int k) {
if(head == null)
return head;
int len = 1;
ListNode temp = head;
while(temp.next != null){
temp = temp.next;
len++;
}
temp.next = head;
int node = (len - k % len);
for(int i = 0;i < node;i++){
temp = temp.next;
}
ListNode res = temp.next;
temp.next = null;
return res;
}
|