Python easy to understand level to level solution


  • 0
    F

    From top to button, level to level from left to right, just need to record the number of node in each level.

    class Solution(object):
    def connect(self, root):
        if not root: return
        stack=collections.deque([root])
        while stack:
            length=len(stack)
            for i in xrange(length):
                node=stack.popleft()
                if node.left: stack+=node.left,
                if node.right: stack+=node.right,
                if i==length-1: node.next=None
                else: node.next=stack[0]

  • 0
    R

    This is not O(1) Solution. This is BFS, its not constant space.


Log in to reply
 

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