一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情。
链表
题目:剑指 Offer 27. 二叉树的镜像
输入一个二叉树,该函数输出它的镜像。
思路:使用tem临时变量存储left,然后交换左右节点的值。
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if (root != null) {
TreeNode temp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(temp);
}
return root;
}
}
时间复杂度:O(N)
空间复杂度:O(N)
题目:剑指 Offer 28. 对称的二叉树
如果一棵二叉树和它的镜像一样,那么它是对称的。
思路:对任意两个对称节点left和right
- left.val=right.val
- left.left=right.right
- left.right=right.left
代码:
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null ? true : recur(root.left, root.right);
}
boolean recur(TreeNode L, TreeNode R) {
if(L == null && R == null) return true;
if(L == null || R == null || L.val != R.val) return false;
return recur(L.left, R.right) && recur(L.right, R.left);
}
}
题目:剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
思路:将当前节点的next指向前一个节点,即cur.next = pre;(需要保存cur.next这个临时变量)
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
时间复杂度:O(N)
空间复杂度:O(1)
题目:剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
题解
思路:先计算链表的长度,然后按照倒序,把数插进去。
class Solution {
public int[] reversePrint(ListNode head) {
ListNode tem = head;
int length = 0;
while(tem != null){
length ++;
tem = tem.next;
}
int[] res = new int[length];
while(head != null){
res[--length]=head.val;
head = head.next;
}
return res;
}
}
题目:剑指 Offer 35. 复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
思路:使用哈希表建立索引,然后再建立联系(next和random)
class Solution {
public Node copyRandomList(Node head) {
if(head==null)return null;
Node cur = head;
Map<Node,Node> map=new HashMap();
while(cur !=null){
map.put(cur,new Node(cur.val));
cur = cur.next;
}
cur = head;
while(cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).random=map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}