采用【分层】BFS写法(通过queue.size()实现)其实不并不难,但此题要求常量级额外空间
————毕竟通过走next,其实并不需要BFS/DFS
class Solution {
/**
*【非递归写法】
* 思路:遍历到某个节点时,不是去将它和某个本层节点连接,而是去连接它的孩子
* 因为采取这种思路,可以保证本节点所在的层的next一定是连好的,因此可以放心用cur.right.next = cur.next.left这种语句
*/
public Node connect(Node root) {
if(root == null){
return root;
}
Node leader = root;
Node cur;
while(leader.left != null){ // leader节点一直是每一层最左边的节点,其实起到了BFS的作用
cur = leader;
while(cur != null){
cur.left.next = cur.right;
if(cur.next != null){
cur.right.next = cur.next.left;
}
cur = cur.next;
}
leader = leader.left;
}
return root;
}
}
class Solution {
/**
*【递归写法】
* 核心还是不变的:连接的不是本节点,而是本节点的孩子们
*/
public Node connect(Node root){
if(root == null){
return root;
}
DFS(root);
return root;
}
private void DFS(Node node){
if(node.left == null){
return;
}
node.left.next = node.right;
if(node.next != null){
node.right.next = node.next.left;
}
DFS(node.left);
DFS(node.right);
}
}
/**
* 1.使用快慢指针法找到链表的中点
* 2.reverseList方法反转中点后的链表
* 3.从头(head)和尾(tail)开始,验证是否为回文
*
* 需要注意的细节有两处:
* 1.快慢指针时,因为当fast.next.next==null时就会停止,所以中点有可能在正中间或者向前取整
* 2.reverseList反转时注意头节点需要改变,并且返回
*/
class Solution {
public boolean isPalindrome(ListNode head) {
// 当[]和[3]的时候,一定时回文
if(head == null || head.next == null){
return true;
}
// 快慢指针法找链表的中点(很经典,背熟写法)
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
// 从头(head)和尾(tail)开始,验证是否为回文
ListNode tail = reverseList2(slow);
while(head != null){
if(head.val != tail.val){
return false;
}else{
head = head.next;
tail = tail.next;
}
}
return true;
}
// 从head节点开始反转链表————非递归(关键:使用三个移动的指针)
private ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode pre = head;
ListNode p = head.next;
ListNode pnext = head.next.next;
head.next = null;
while(pnext != null){
p.next = pre;
pre = p;
p = pnext;
pnext = pnext.next;
}
p.next = pre;
return p;
}
// 从head节点开始反转链表————递归(关键:假设head之后的节点已经反转好了)
private ListNode reverseList2(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode tail = reverseList2(head.next);
head.next.next = head;
head.next = null;
return tail;
}
}
这道题考察点其实并不单一————快慢指针找链表中点、反转链表...
所以说,《数据结构》中的基础知识是重中之重,如果做不到熟练掌握,这道题根本不"easy"
Qs from https://leetcode-cn.com
♥ loli suki
♠ end