Same Python code as problem 116


  • 0
    W
    # 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 root==None:
                return root
            q,height,keep_height=[],1,1
            q.append((root,1))
            pre_node=root
            while q:
                node,height=q.pop(0)
                if height==keep_height+1:
                    pre_node.next=None
                elif height==keep_height:
                    pre_node.next=node
                keep_height=height
                pre_node=node
                if node.left:
                    q.append((node.left,height+1))
                if node.right:
                    q.append((node.right,height+1))
            pre_node.next=None

Log in to reply
 

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