1. 题目描述
2. Solution 1
1、思路分析
类似层次遍历,无须使用队列,使用已建立好的next指针,跳到下一层。
2、代码实现
package Q0199.Q0117PopulatingNextRightPointersinEachNodeII;
import DataStructure.Node;
public class Solution {
public Node connect(Node root) {
Node head = root;
while (head != null) {
Node dummy = new Node(0); // 每一层设置一个链表头结点,用于统一插入操作
Node cur = dummy;
while (head != null) {
if (head.left != null) {
cur.next = head.left;
cur = cur.next;
}
if (head.right != null) {
cur.next = head.right;
cur = cur.next;
}
head = head.next;
}
head = dummy.next; // 下一层
}
return root;
}
}
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)