题目链接
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
题目原文
题目大意
和上一题类似,但是可能会有些节点没有左子树或者右子树
解题思路
使用层次遍历:
- 临时节点指向根节点的左子树,如果左子树存在,临时节点下移;如果不存在,临时节点指向根节点的右子树;如果右子树存在,临时节点下移
- 根节点下移,如果根节点不为空,重复步骤1,否则,重置临时节点,将根节点移至下一层的首节点
代码
# 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
"""
node = tmp = TreeLinkNode(0)
while root:
node.next = root.left
if node.next:
node = node.next
node.next = root.right
if node.next:
node = node.next
root = root.next
if not root:
node = tmp
root = node.next