leetcood学习笔记-226- 翻转二叉树

题目描述:

第一次提交:

class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        temp = root.left
        root.left = root.right
        root.right = temp#    root.left,root.right = root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

可缩减代码:

class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root :
            return root
        else:
            root.left,root.right=self.invertTree(root.right),self.invertTree(root.left)
            return root

猜你喜欢

转载自www.cnblogs.com/oldby/p/10611392.html