226_翻转二叉树

"""
翻转一棵二叉树。

示例:
输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

"""
# 时间复杂度 72%
def invertTree(root):
    if not root:
        return None

    def helper(root):
        if not root:
            return
        helper(root.right)
        helper(root.left)
        tmp = root.right
        root.right = root.left
        root.left = tmp
    helper(root)
    return root

# 时间复杂度更低 99%
def invertTree(self, root: TreeNode) -> TreeNode:
    if not root:
        return None

    def helper(root):
        if not root:
            return None
        root.left, root.right = root.right, root.left
        helper(root.right)
        helper(root.left)

    helper(root)
    return root

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页