题目:
翻转一棵二叉树。
解题思路:
用递归解法,递归遍历树的每个节点,将左右子树互换
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root==None:
return root
root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
return root