Leetcode 226. Invert Binary Tree

Invert a binary tree.

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

to

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

使用递归的trival solution
 1 class Solution(object):
 2     def invertTree(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: TreeNode
 6         """
 7         if not root:
 8             return
 9         
10         root.left, root.right = root.right, root.left
11         self.invertTree(root.right)
12         self.invertTree(root.left)
13         
14         return root
15         

 

非递归的话,需要一个queue辅助。

 1 class Solution(object):
 2     def invertTree(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: TreeNode
 6         """
 7         if not root:
 8             return
 9         
10         queue = [root]
11         
12         while queue:
13             node = queue.pop(0)
14             if node.left:
15                 queue.append(node.left)
16             if node.right:
17                 queue.append(node.right)
18             node.left, node.right = node.right, node.left
19         
20         return root
21             
22             

 

posted @ 2016-11-21 10:55  lettuan  阅读(153)  评论(0编辑  收藏  举报