96ms easy to understand python solution with inline comments


  • 0
    Y
    class Solution(object):
    def connect(self, root):
        """
        :type root: TreeLinkNode
        :rtype: nothing
        """
        def getFirstChild(node):
            while node:
                if node.left: return node.left
                if node.right: return node.right
                node = node.next
            return None
            
        if not root: return
        prev = root
        curr = None
        while getFirstChild(prev):  #next level has node
            curr = prev # prev is the first node at the level
            while curr: 
                if curr.left and curr.right:
                    curr.left.next = curr.right
                    curr.right.next = getFirstChild(curr.next)
                elif curr.left:
                    curr.left.next = getFirstChild(curr.next)
                elif curr.right:
                    curr.right.next = getFirstChild(curr.next)
                curr = curr.next
            prev = getFirstChild(prev)

Log in to reply
 

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