Populating Next Right Pointers in Each Node II(BFS)
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next;} 1 / \ 2 3 / \ \4 5 7 1 -> NULL / \ 2 -> 3 -> NULL / \ \4-> 5 -> 7 -> NULL# Definition for binary tree with next pointer.# class TreeLinkNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = None# self.next = Noneclass Solution: # @param root, a tree link node # @return nothing def connect(self, root): if not root: return root q=[root] while q: n = len(q) for i in range(n): cur = q.pop(0) if i == n-1: cur.next =None else: cur.next = q[0] if cur.left: q.append(cur.left) if cur.right: q.append(cur.right)class Solution:
def connect(self, root):
while root:
dummy = TreeLinkNode(0)
curc = dummy
while root:根据本层的遍历连接孩子层
if root.left:
curc.next = root.left
curc = curc.next
if root.right:
curc.next = root.right
curc = curc.next
root = root.next
root = dummy.next #root设置为孩子层 Last updated