python invert binary tree

40

from collections import deque
def levelOrderTraversal(root):
    q = deque()
    q.append(root)
    while q:
        curr = q.popleft()
        print(curr.data, end=' ')
        if curr.left:
            q.append(curr.left)
        if curr.right:
            q.append(curr.right)
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
    head = root

    def _invert_tree(node):
        if not node:
            return

        node.left, node.right = node.right, node.left
        _invert_tree(node.left)
        _invert_tree(node.right)

    _invert_tree(root)

    return head

Comments

Submit
0 Comments