Straight-forward Python Solution


  • 0
    J
    class Solution:
        def connect(self, root):
            if not root or not root.left:
                return
            queue = [root]
            nextrow = []
            while len(queue) > 0:
                e = queue.pop(0)
                if e.left is not None:
                    nextrow.append(e.left)
                    nextrow.append(e.right)
                if len(queue) > 0:
                    e.next = queue[0]
                else:
                    queue = nextrow
                    nextrow = []
    

    Basic idea is to keep a list of whats on the next row, which also gives you the order of what's next. by cycling through the queue, you preserve the order of the leaves to connect them in order. I'm sure there's a more efficient way that doesn't require two lists, but this made the most sense to me and it's O(n).


Log in to reply
 

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