题目链接:Invert Binary Tree
思路:
如果需要反转一个二叉树,那么我们需要遍历整个树的所有节点。
如果想遍历所有的节点,我们可以用Depth First Search(DFS)或者Breadth First Search(BFS)。
这两种办法分别可以用迭代(iterative)或者递归(recursive)的办法实现。
算法复杂度:
递归:
时间:O(n) where n is the number of nodes
空间:O(n)
DFS/BFS:
时间:O(n) where n is the number of nodes
空间:O(n)
代码:
递归:
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
DFS (Stack):
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.extend([node.right, node.left])
return root
BFS (Queue):
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
queue = [root]
while queue:
node = queue.pop(0)
if node:
node.left, node.right = node.right, node.left
queue.extend([node.left, node.right])
return root