【Leetcode】116. Populating Next Right Pointers in Each Node

class Solution:

    # @param root, a tree link node

    # @return nothing

    def connect(self, root):

        if not root:

            return

        while root.left:

            level = root.left

            cur = None

            while root:

                root.left.next = root.right

                cur = root.right

                root = root.next

                if cur and root:

                    cur.next = root.left

            root = level

1 因为是perfect binary tree,所以所有叶子节点都在一个level上,而且每一个internal node都有两个children

2 BFS不能用queue来做,因为会有extra space

3 最外面一个while循环,循环条件是root.left

4 将当前节点root的root.left和root.right连接起来后(root.left.next=root.right),我们需要再将root.right和root.next.left连接起来,直到root.next不再存在

5 在init里,self.next = None已经

6 if not root: return 不能写成if not root: return None 这道题并没有返回值,不能用return None

你可能感兴趣的:(【Leetcode】116. Populating Next Right Pointers in Each Node)