Python three method: DFS,BFS,recursive


  • -1
    #226 Invert Binary Tree
    #recursive method
    def invertTree(root):
        if root:
            root.left, root.right = invertTree(root.right), invertTree(root.left)
            return root
    # iterative method, dfs
            if root:
                stack = []
                stack.append(root)
                while stack:
                    node = stack.pop()
                    node.left, node.right = node.right, node.left
                    if node.left:
                        stack.append(node.left)
                    if node.right:
                        stack.append(node.right)
            return root
    # iterative method, bfs
            if root:
                stack = []
                stack.append(root)
                for node in stack:
                    node.left, node.right = node.right, node.left
                    if node.left:
                        stack.append(node.left)
                    if node.right:
                        stack.append(node.right)
            return root
    

Log in to reply
 

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