LeetCode 117 Populating Next Right Pointers in Each Node II

LeetCode 117 Populating Next Right Pointers in Each Node II Problem

Download Code
# 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
    #     """
    # level by level
    #     if root is None:
    #         return
    #     nodes = [root]
    #     while len(nodes) != 0:
    #         next_step = []
    #         last = None
    #         for node in nodes:
    #             if last is not None:
    #                 last.next = node
    #             if node.left is not None:
    #                 next_step.append(node.left)
    #             if node.right is not None:
    #                 next_step.append(node.right)
    #             last = node
    #         nodes = next_step

    def connect(self, root):
        # https://discuss.leetcode.com/topic/28580/java-solution-with-constant-space
        dummyHead = TreeLinkNode(-1)
        pre = dummyHead
        while root is not None:
            if root.left is not None:
                pre.next = root.left
                pre = pre.next
            if root.right is not None:
                pre.next = root.right
                pre = pre.next
            root = root.next
            if root is None:
                pre = dummyHead
                root = dummyHead.next
                dummyHead.next = None


List of all Populating Next Right Pointers in Each Node II problems

Leetcode 117 Populating Next Right Pointers in Each Node II problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

self.val = x

self.left = None

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.