-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path117. Populating Next Right Pointers in Each Node II.py
43 lines (41 loc) · 1.53 KB
/
117. Populating Next Right Pointers in Each Node II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if root:
pre = root
while pre:
if pre.left or pre.right:
pass
else:
pre = pre.next
continue
cur = pre
while cur:
# find cur.left.next
if cur.left:
if cur.right:
cur.left.next = cur.right
else:
tem = cur.next
while tem:
if tem.left:
cur.left.next = tem.left
break
elif tem.right:
cur.left.next = tem.right
break
tem = tem.next
# find cur.right.next
if cur.right:
tem = cur.next
while tem:
if tem.left:
cur.right.next = tem.left
break
elif tem.right:
cur.right.next = tem.right
break
tem = tem.next
cur = cur.next
pre = pre.left if pre.left else pre.right