"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
start = root
while start:
self.last = None
self.nextStart = None
p = start
while p:
if p.left:
self.handle(p.left)
if p.right:
self.handle(p.right)
p = p.next
start = self.nextStart
return root
def handle(self, p):
if self.last:
self.last.next = p
if not self.nextStart:
self.nextStart = p
self.last = p
/**
* Definition for a Node.
* type Node struct {
* Val int
* Left *Node
* Right *Node
* Next *Node
* }
*/
func connect(root *Node) *Node {
start := root
for start != nil {
var nextStart, last *Node
handle := func(cur *Node) {
if cur == nil {
return
}
if nextStart == nil {
nextStart = cur
}
if last != nil {
last.Next = cur
}
last = cur
}
for p := start; p != nil; p = p.Next {
handle(p.Left)
handle(p.Right)
}
start = nextStart
}
return root
}
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
cur = root
while cur:
head = Node(0)
tail = head
p = cur
while p:
if p.left:
tail.next = p.left
tail = tail.next
if p.right:
tail.next = p.right
tail = tail.next
p = p.next
cur = head.next
return root
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if (root == null)
return root;
//cur我们可以把它看做是每一层的链表
Node cur = root;
while (cur != null) {
//遍历当前层的时候,为了方便操作在下一
//层前面添加一个哑结点(注意这里是访问
//当前层的节点,然后把下一层的节点串起来)
Node dummy = new Node(0);
//pre表示访下一层节点的前一个节点
Node pre = dummy;
//然后开始遍历当前层的链表
while (cur != null) {
if (cur.left != null) {
//如果当前节点的左子节点不为空,就让pre节点
//的next指向他,也就是把它串起来
pre.next = cur.left;
//然后再更新pre
pre = pre.next;
}
//同理参照左子树
if (cur.right != null) {
pre.next = cur.right;
pre = pre.next;
}
//继续访问这一行的下一个节点
cur = cur.next;
}
//把下一层串联成一个链表之后,让他赋值给cur,
//后续继续循环,直到cur为空为止
cur = dummy.next;
}
return root;
}
}