Straight-forward Python Solution

  • 0
    class Solution:
        def connect(self, root):
            if not root or not root.left:
            queue = [root]
            nextrow = []
            while len(queue) > 0:
                e = queue.pop(0)
                if e.left is not None:
                if len(queue) > 0:
           = queue[0]
                    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.