目录
LeetCode226. 翻转二叉树
1. 思路
我们之前介绍的都是各种方式遍历二叉树,这次要翻转了,感觉还是有点懵逼。
这得怎么翻转呢?如果要从整个树来看,翻转还真的挺复杂,整个树以中间分割线进行翻转,如图:
可以发现想要翻转它,其实就把每一个节点的左右孩子交换一下就可以了。
关键在于遍历顺序,前中后序应该选哪一种遍历顺序? (一些同学这道题都过了,但是不知道自己用的是什么顺序)
遍历的过程中只要把每一个节点的左右孩子翻转一下,就可以达到整体翻转的效果。这道题目使用前序遍历和后序遍历都可以,唯独中序遍历不方便,因为中序遍历(递归法)会把某些节点的左右孩子翻转了两次!建议拿纸画一画,就理解了。那么层序遍历可以不可以呢?依然可以的!只要把每一个节点的左右孩子翻转一下的遍历方式都是可以的!
中序遍历为啥不行?
以上面的二叉树为例,中序为左中右,先处理4的左孩子,把1和3交换顺序之后,再处理中节点,把2及其子树和7及其子树交换位置,现在该处理右节点了,但是发现右节点是之前处理过了的节点2及其子树,所以节点2及其子树会交换两遍,节点7及其子树没有处理。
2. 代码实现
用遍历二叉树的各种方法都可以实现,一共有10种。
包括递归法(前中后序)迭代法(前中后序)统一迭代法(前中后序)层序遍历
这里以前序递归为例实现:
# 前序递归实现 翻转二叉树 中左右
# time:O(N);space:O(N)
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None: return # base case
root.left, root.right = root.right,root.left #中
self.invertTree(root.left) # 左
self.invertTree(root.right) # 右
return root
2.1 递归法实现(前中后序)
# 翻转二叉树 递归法
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 递归 前序遍历
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None: return None
root.left,root.right = root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
# 递归 后序遍历
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None: return None
self.invertTree(root.left)
self.invertTree(root.right)
root.left,root.right = root.right,root.left
return root
# 递归 中序遍历
# time:O(N) space:O(logN)
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None: return None
self.invertTree(root.left)
root.left,root.right = root.right,root.left
# 这里还是要翻转左孩子,因为上面左右互换了
self.invertTree(root.left)
return root
2.2 迭代法(前中后序)
# 迭代法 前序遍历
# time:O(N);space:O(N)
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None: return None
stack = [root]
while stack:
node = stack.pop()
node.left,node.right = node.right,node.left
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
return root
# 迭代法 中序遍历
# time O(N) space:O(N)
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None: return None
stack = []
cur = root
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
cur.left,cur.right = cur.right,cur.lef