题目:
给定一个二叉树,将其对称反转。样例如下。
解题思路:
可以发现只要将二叉树从根节点出发,把每一个节点的左子树和右子树对称交换,即可得到整个二叉树的对称交换结果。故使用递归进行反转
代码(Python):
# 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
"""
def Iteration(root):
if root==None:
return
else:
temp = root.left
root.left = root.right
root.right = temp
Iteration(root.left)
Iteration(root.right)
Iteration(root)
return root