python leetcode刷题 (15):226. 翻转二叉树

题目描述:

翻转一棵二叉树。

示例:
python leetcode刷题 (15):226. 翻转二叉树_第1张图片

解题流程:

第一反应是递归,翻评论区找到了左右互换的方法:使用中间变量t:

# 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 root==None:
            return root
        t=self.invertTree(root.left)
        root.left=self.invertTree(root.right)
        root.right=t
        return root

总结:

  1. 许多二叉树变换的题目需要递归;
  2. root==None时需要返回root。

你可能感兴趣的:(python刷题)