Skip to content

Commit 40693b8

Browse files
committed
117 Populating Next Right Pointers in Each Node II
1 parent 26998c1 commit 40693b8

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'''
2+
Follow up for problem "Populating Next Right Pointers in Each Node".
3+
4+
What if the given tree could be any binary tree? Would your previous solution still work?
5+
6+
Note:
7+
8+
You may only use constant extra space.
9+
For example,
10+
Given the following binary tree,
11+
1
12+
/ \
13+
2 3
14+
/ \ \
15+
4 5 7
16+
After calling your function, the tree should look like:
17+
1 -> NULL
18+
/ \
19+
2 -> 3 -> NULL
20+
/ \ \
21+
4-> 5 -> 7 -> NULL
22+
'''
23+
24+
# Definition for binary tree with next pointer.
25+
class TreeLinkNode(object):
26+
def __init__(self, x):
27+
self.val = x
28+
self.left = None
29+
self.right = None
30+
self.next = None
31+
32+
33+
class Solution(object):
34+
def connect(self, root):
35+
"""
36+
:type root: TreeLinkNode
37+
:rtype: nothing
38+
"""
39+
prekid = kid = TreeLinkNode(0)
40+
while root:
41+
while root:
42+
kid.next = root.left
43+
kid = kid.next or kid
44+
kid.next = root.right
45+
kid = kid.next or kid
46+
root = root.next
47+
root, kid = prekid.next, prekid
48+
49+
50+
if __name__ == "__main__":
51+
None

0 commit comments

Comments
 (0)