leetcode-mid-Linked list- 116. Populating Next Right Pointers in Each Node

mycode   93.97%

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution(object):
    def connect(self, root):
        if not root:
            return None
        
        if root and root.left:
            root.left.next = root.right
            if root.next != None:
                #print(root.val,root.next)
                root.right.next = root.next.left
            self.connect(root.left)
            self.connect(root.right)
        return root

reference:

In fact, if you can write only the second root.left, so wide with a fast Diudiu friends

class Solution(object):
    def connect(self, root):
        """
        :type root: Node
        :rtype: Node
        """
        if not root:
            return None
        if root.left:
            root.left.next = root.right
            if root.next:
                root.right.next = root.next.left
            self.connect(root.left)
            self.connect(root.right)
        return root

 

Guess you like

Origin www.cnblogs.com/rosyYY/p/10968584.html