Elegant python solution, easy logic


  • 0
    Y
    # 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
            """
            pre = root
            first_child = None
            pre_child = None
            next_child = None
            while pre:
                if pre.left:
                    if not first_child:
                        first_child = pre.left
                    if not pre_child:
                        pre_child = pre.left
                    elif not next_child:
                        pre_child.next = pre.left
                        pre_child = pre.left
                        
                if pre.right:
                    if not first_child:
                        first_child = pre.right
                    if not pre_child:
                        pre_child = pre.right
                    elif not next_child:
                        next_child = pre.right
                        
                if pre_child and next_child:
                    pre_child.next = next_child
                    pre_child = pre_child.next
                    next_child = None
                if pre.next:
                    pre = pre.next
                elif first_child:
                    pre = first_child
                    first_child = None
                    pre_child = None
                    next_child = None
                else:
                    return
                    
    

    Keep track of previous child and next child, link them.
    Keep track of the first occurring child, when need to go to next depth, got to that child, done.


Log in to reply
 

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