leetcode @python 117. Populating Next Right Pointers in Each Node II.py

题目链接

https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

题目原文

题目大意

和上一题类似,但是可能会有些节点没有左子树或者右子树

解题思路

使用层次遍历:

  1. 临时节点指向根节点的左子树,如果左子树存在,临时节点下移;如果不存在,临时节点指向根节点的右子树;如果右子树存在,临时节点下移
  2. 根节点下移,如果根节点不为空,重复步骤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
posted @ 2016-03-25 11:25  slurm  阅读(399)  评论(0编辑  收藏  举报