Iterative python solution using level order traversal


  • 0
    T
    class Solution:
        # @param root, a tree link node
        # @return nothing
        def connect(self, root):
            currNodes = [root, ]
            while currNodes:
                prevNodes, currNodes = currNodes, []
                while prevNodes:
                    node = prevNodes.pop(0)
                    if not node:
                        continue
                    if node.left:
                        currNodes.append(node.left)
                    if node.right:
                        currNodes.append(node.right)
                for i, node in enumerate(currNodes):
                    try:
                        node.next = currNodes[i+1]
                    except:
                        pass
    

    Easy to understand, but a little bit slow. Could anyone improve that for me?


Log in to reply
 

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