-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathPopulatingNextRightPointersInEachNodeII.py
More file actions
41 lines (39 loc) · 1.12 KB
/
PopulatingNextRightPointersInEachNodeII.py
File metadata and controls
41 lines (39 loc) · 1.12 KB
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
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
if not root:
return
self.connect(root.left)
self.connect(root.right)
left=root.left
right=root.right
while left and right:
last=left
while last.next:
last=last.next
while left.left is None and left.right is None:
left=left.next
if not left:
last.next=right
return
last.next=right
if left.left:
left=left.left
else:
left=left.right
while right.left is None and right.right is None:
right=right.next
if not right:
return
if right.left:
right=right.left
else:
right=right.right