BFS solution in python


  • 0
    F

    Simple idea, traversal by level, in each level, set previous node's next to next node.

    class Solution(object):
        def connect(self, root):
            """
            :type root: TreeLinkNode
            :rtype: nothing
            """
            if not root:return
            thislevel=[root]
            while thislevel:
                nextlevel=list()
                pre=None
                for node in thislevel:
                    if not pre:
                        pre=node
                    else:
                        pre.next=node
                        pre=node
                    if node and node.left:
                        nextlevel.append(node.left)
                    if node and node.right:
                        nextlevel.append(node.right)
                thislevel=nextlevel

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.