Solution by python using level traverse and queue


  • 0
    M

    Solution by python using level traverse and queue

    # Definition for binary tree with next pointer.
    # class TreeLinkNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    #         self.next = None
    
    class Solution:
        # @param root, a tree link node
        # @return nothing
        def connect(self, root):
            if not root:
                return
            
            queue = [root]
            step = 1
            
            while queue:
                pre = queue[0]
                del(queue[0])
                if pre.left:
                    queue.append(pre.left)
                if pre.left:
                    queue.append(pre.right)
                for i in range(step-1):
                    pre.next = queue[0]
                    del(queue[0])
                    pre = pre.next
                    if pre.left:
                        queue.append(pre.left)
                    if pre.left:
                        queue.append(pre.right)
                step = step * 2    
                
            return
                    
            
            
    

Log in to reply
 

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