#Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
Tree1 = TreeNode(4)
Tree1.left = TreeNode(2)
Tree1.right = TreeNode(7)
Tree1.left.left = TreeNode(1)
Tree1.left.right = TreeNode(3)
Tree1.right.left = TreeNode(6)
Tree1.right.right = TreeNode(9)
preorder(Tree1)
print('.....................')
s = Solution()
res = s.invertTree(Tree1)
preorder(res)
print(res)
'''
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
'''
python invertTree 反转二叉树
最新推荐文章于 2023-02-03 10:41:11 发布