Python straightforward solution


  • 0
    P
    class Solution:
        # @param root, a tree link node
        # @return nothing
        def connect(self, root):
            if root:
                stack = [[root]]
                while True:
                    temp = []
                    for node in stack[-1]:
                        if node.left:   temp.append( node.left )
                        if node.right:  temp.append( node.right )
                    if not temp:    
                        break
                    stack.append(temp)
                for nodes in stack:
                        for node1, node2 in zip(nodes[:-1], nodes[1:]):
                            node1.next = node2
    

    temp stores all the nodes on the same level
    satck stores all the levels


Log in to reply
 

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