题目:
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
题目的理解:
采用递归的方式进行遍历二叉树,然后交换left和right。
python实现
# 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: TreeNode) -> TreeNode:
current = root
self.invert(root)
return current
def invert(self, node: TreeNode):
if node is None:
return
temp = node.left
node.left = node.right
node.right = temp
self.invert(node.left)
self.invert(node.right)
提交
成功// END 什么时候可以上班呢
网友评论