Invert Binary Tree

Question

https://leetcode.com/problems/invert-binary-tree/?tab=Description

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Tags

  • tree

Analysis

This problem requires to know the traversal approach for a tree. Usually there are three different ways to go through a tree: preorder, inorder and postorder. In the implementation, recursion or list can be used.

Here since the order is not important, thus we use a queue to implement the preorder algorithm for the binary tree.

code:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return None
        queue = [root]
        while queue != []:
            ptr = queue[0]
            del queue[0]
            ptr.left, ptr.right = ptr.right, ptr.left
            if ptr.left is not None:
                queue.append(ptr.left)
            if ptr.right is not None:
                queue.append(ptr.right)
        return root

results matching ""

    No results matching ""