Populating Next Right Pointers in Each Node

Problem: Populating Next Right Pointers in Each Node

We can use depth-first search to deal with this problem. When we write a depth-first search function, we need to add right neighbor into the arguments this time.

Code in Python:

class Solution(object):
    def connect(self, root):
        """
        :type root: TreeLinkNode
        :rtype: nothing
        """
        def dfs(node, next):
            node.next = next
            if not node.left: return
            dfs(node.left, node.right)
            if next: dfs(node.right, next.left)
            else: dfs(node.right, None)

        if not root: return
        dfs(root, None)

results matching ""

    No results matching ""