python - next pointers


  • 0
    S
    # 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 root:
                queue = [root]
                while queue:               
                    tmpq = []
                    for node in queue:
                        if node.left:
                            if tmpq: tmpq[-1].next = node.left
                            tmpq.append(node.left)
                        if node.right:
                            if tmpq: tmpq[-1].next = node.right
                            tmpq.append(node.right)
                    
                    queue = tmpq
    

Log in to reply
 

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