Easiest to understand! Recursive solution in Python

  • 1
    class Solution:
        def connect(self, root):
            self.connectNodes(root, [])
        #This recursive function connect root and right nodes with nodes in parameter, and return left most nodes
        def connectNodes(self, root, nodesToConnect):
            if not root:
                return nodesToConnect
            if nodesToConnect:
                root.next = nodesToConnect.pop()
            rightNodes = self.connectNodes(root.right, nodesToConnect)
            leftNodes = self.connectNodes(root.left, rightNodes)
            return leftNodes + [root]

Log in to reply

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