翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
解题思路
这是一道非常有名的题目,有名的地方不是因为这个问题的难度或者背后的数学知识,而是因为这是Homebrew
(一个软件包管理器)的作者面试谷歌时候被提到的问题,并且他没有答出来,但是这个问题非常简单,当然这背后可能有什么原因,我们不去管他,我们来看看这个问题该怎么解就好了。
这个问题使用递归很好解决,我们只要先invertTree(root.left and root.right)
,然后再交换root.left
和root.right
。我们只要明确好函数的意义,那么这个问题就很简单。
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
self.invertTree(root.left)
self.invertTree(root.right)
root.left, root.right = root.right, root.left
return root
同样的,对于可以用递归解决的问题,我们都应该思考一下怎么可以通过迭代去解决。那这个问题怎么通过迭代解决呢?那么我们就会用到stack
,通过stack
模拟上面的递归过程。一个较为简单的思路就是二叉树的层序遍历,参看这篇Leetcode 102:二叉树的层次遍历(最详细解决方案!!!) ,我们在此基础上稍加修改就可以了。
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
q = [root]
while stack:
node = q.pop(0)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
node.left, node.right = node.right, node.left
return root
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!