Skip to content

Commit a79e328

Browse files
committed
填充每个节点的下一个右侧节点指针 II
1 parent 116d892 commit a79e328

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

tree/117_connect.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -39,24 +39,18 @@ def connect_o1(self, root: 'Node') -> 'Node':
3939
return root
4040

4141
leftmost = root
42-
while leftmost.left:
43-
head = leftmost
44-
45-
while head:
46-
head.left.next = head.right
47-
if head.next:
48-
head.right.next = head.next.left
49-
head = head.next
50-
leftmost = leftmost.left
51-
42+
while leftmost:
43+
head = tail = Node()
44+
cur = leftmost
45+
46+
while cur:
47+
if cur.left:
48+
tail.next = cur.left
49+
tail = tail.next
50+
if cur.right:
51+
tail.next = cur.right
52+
tail = tail.next
53+
cur = cur.next
54+
leftmost = head.next
5255
return root
5356

54-
def connect_rec(self, root: 'Node') -> 'Node':
55-
if not root:
56-
return root
57-
root.left.next = root.right
58-
if root.next:
59-
root.right.next = root.next.left
60-
self.connect_rec(root.left)
61-
self.connect_rec(root.right)
62-
return root

0 commit comments

Comments
 (0)