Easy to understand Level-order Python Solution


  • 0
    Z
    # Definition for binary tree with next pointer.
    # class TreeLinkNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    #         self.next = None
    
    class Solution(object):
        def connect(self, root):
            """
            :type root: TreeLinkNode
            :rtype: nothing
            """
            if not root:
                return
            queue=collections.deque([root])
            temp=collections.deque()
            count=1
            while queue:
                for i in range(count):
                    node=queue.popleft()
                    if node:
                        queue.append(node.left)
                        queue.append(node.right)
                        temp.append(node)
                count*=2
                next=None
                while temp:
                    node=temp.pop()
                    node.next,next=next,node

  • 0

    BFS is too trivial and banned by the constant space constraint.


Log in to reply
 

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