Description
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution
本质就是一个后序遍历。先对子节点进行翻转,逐渐向树根靠近翻转。
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
def invert(root):
if not root: return None
left = invert(root.left)
right = invert(root.right)
root.left, root.right = right, left
return root
return invert(root)