What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
Example,
Given the following binary tree,
1
2
3
4
5
| 1
/ \
2 3
/ \ \
4 5 7
|
After calling your function, the tree should look like:
1
2
3
4
5
| 1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
|
Solution
- 一个firstnode记录每行第一个节点
- 一行一行遍历,没遍历一行把节点的字节点们都连好
- 一个lastNode记录上次访问节点
(Populating-next-right-pointers-in-each-node2.py) download
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
| # 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):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
def connectNode(prev,node):
# 有可能送进来的是第一个节点
if prev != None:
prev.next = node
if root == None:
return None
parent = root
root.next = None
while parent:
# 每一行第一个节点
firstNode = None
# 上一次链接的节点
lastNode = None
# 循环一次可以把一整行的节点的字节点连接好
while parent is not None:
for node in [parent.left,parent.right]:
if node == None:
continue
# 当拿到右边节点的时候才会链接
connectNode(lastNode,node)
# 碰到了每一行的第一个节点
if lastNode == None:
firstNode = node
lastNode = node
parent = parent.next
parent = firstNode
|