Python solution

  • 0
    class Solution:
        # @param root, a tree link node
        # @return nothing
        def connect(self, root):
        	def leftMost(node):
        		while node is not None:
        			if node.left is not None:
        				return node.left
        			elif node.right is not None:
        				return node.right
        			node =
        	while root is not None:
        		p = root
        		while p is not None:
        			if p.left is not None and p.right is not None:
   = p.right
   = leftMost(
        			elif p.left is not None:
   = leftMost(
        			elif p.right is not None:
   = leftMost(
        			p =
        		root = leftMost(root)

Log in to reply

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