117. Populating Next Right Pointers in Each Node II


Given a binary tree struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.

  • code
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return None
        thislevel = [root]
        while thislevel:
            for i in range(len(thislevel)):
                if i == len(thislevel)-1:
                    thislevel[i].next = None
                    thislevel[i].next = thislevel[i+1]
            thislevel = [i for node in thislevel for i in (node.left, node.right) if i]
        return root