LeetCode 226 Invert Binary Tree 解题报告

时间:2022-07-01 15:05:12

题目要求

Invert a binary tree.

题目分析及思路

给定一棵二叉树,要求每一层的结点逆序。可以使用递归的思想将左右子树互换。

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:

if not root:

return

right = self.invertTree(root.right)

left = self.invertTree(root.left)

root.left = right

root.right = left

return root