Python BFS using queue


  • 0
    class Solution(object):
        def addOneRow(self, root, v, d):
            """
            :type root: TreeNode
            :type v: int
            :type d: int
            :rtype: TreeNode
            """
            if d == 1:
                node = TreeNode(v)
                node.left = root
                return node
            queue = collections.deque([(root, 1)])
            level = 0
            while queue and level < d:
                node, level = queue.popleft()
                if level == d-1:
                    left, right = node.left, node.right
                    node.left = TreeNode(v)
                    node.right = TreeNode(v)
                    node.left.left, node.right.right = left, right
                else:
                    if node.left: queue.append((node.left, level+1))
                    if node.right: queue.append((node.right, level+1))
            return root
    

  • 0
    T

    brief code....
    I just use the list..


Log in to reply
 

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