Skip to content

Commit d372d59

Browse files
committed
填充每个节点的下一个右侧节点指针
1 parent d0368e9 commit d372d59

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

tree/117_connect.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None,
1414
class Solution:
1515
def connect(self, root: 'Node') -> 'Node':
1616
if not root:
17-
return
17+
return root
1818

1919
q = collections.deque()
2020
q.append(root)
@@ -33,3 +33,30 @@ def connect(self, root: 'Node') -> 'Node':
3333
last.next = node
3434
last = node
3535
return root
36+
37+
def connect_o1(self, root: 'Node') -> 'Node':
38+
if not root:
39+
return root
40+
41+
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+
52+
return root
53+
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)