116.填充每个节点的下一个右侧节点指针(递归+迭代)
class Solution {
public Node connect(Node root) {
if(root == null) return null;
Node pre = root;
while(pre.left != null) {
Node temp = pre;
while(temp != null) {
temp.left.next = temp.right;
if(temp.next != null) temp.right.next = temp.next.left;
temp = temp.next;
}
pre = pre.left;
}
return root;
}
}
117.填充每个节点的下一个右侧节点指针II(递归+迭代)
class Solution {
public Node connect(Node root) {
if(root == null) return null;
Node cur = root;
Node dummy = new Node(0);
while(cur != null) {
Node pre = dummy;
while(cur != null) {
if(cur.left != null) {
pre.next = cur.left;
pre = pre.next;
}
if(cur.right != null) {
pre.next = cur.right;
pre = pre.next;
}
cur = cur.next;
}
cur = dummy.next;
dummy.next = null;
}
return root;
}
}