Given a binary tree
struct Node { int val; Node *left; Node *right; Node *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
用层序遍历的方式,把每一层节点存在一个list中。
然后进行处理比较容易。
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root is None:return root
level = [root]
root.next=None
while level:
temp=[]
for i in range(len(level)-1):
level[i].next=level[i+1]
for node in level:
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
level=temp
return root