226. 翻转二叉树3
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
思路:反转二叉树也叫镜像二叉树,通过递归将左子树的左孩子右孩子和右节点的右孩子左孩子交换。
# 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
"""
if not root:
return root
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
---------------------
作者:Cytues
来源:CSDN
原文:https://blog.csdn.net/qq_41805514/article/details/82807765
版权声明:本文为博主原创文章,转载请附上博文链接!