-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path116_PopulatingNextRightPointersInEachNode.py
61 lines (49 loc) · 1.44 KB
/
116_PopulatingNextRightPointersInEachNode.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for binary tree with next pointer.
# class TreeLinkNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution(object):
def connect(self, root):
if not root:
return None
cur_head = root
next_head = None
# Breadth-first Scan
while cur_head:
if cur_head.left:
# Get the next level's head
if not next_head:
next_head = cur_head.left
cur_head.left.next = cur_head.right
if cur_head.right and cur_head.next:
cur_head.right.next = cur_head.next.left
cur_head = cur_head.next
# Go to next level.
if not cur_head:
cur_head = next_head
next_head = None
""" Readable implementation
class Solution(object):
def connect(self, root):
# For all the non-empty nodes:
# node.left.next = node.right
# node.right.next = node.next.left(if node.next not none)
if not root:
return None
if root.left:
root.left.next = root.right
if root.next and root.right:
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
"""
"""
[0]
[1,2,3]
[0,1,2,3,4,5,6]
"""