Invert Binary Tree

Problem

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Intuition

The problem requires inverting a binary tree, which means swapping the left and right subtrees for each node. This operation essentially reflects the binary tree across its vertical axis. The goal is to transform the given tree into its mirror image.

Approach

Base Case: Check if the root is None (empty tree). If so, return None.
Swap Left and Right Subtrees: Swap the left and right subtrees of the current root node.
Recursion: Recursively apply the same inversion process to the left and right subtrees.
Return Root: Return the root of the modified tree.

Complexity

  • Time complexity:

The time complexity of this solution is O(n), where n is the number of nodes in the binary tree. The function visits each node exactly once, and the inversion operation (swapping left and right subtrees) takes constant time.

  • Space complexity:

The space complexity is O(h), where h is the height of the binary tree. In the worst case, the function call stack will have a maximum depth equal to the height of the tree. This is because the recursion is depth-first, and the space required on the call stack is proportional to the height of the tree. In the average case, for a balanced binary tree, the height is O(log n), making the space complexity O(log n). However, in the worst case of an unbalanced tree, the height could be O(n), resulting in a space complexity of O(n).

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None

        temp = root.left
        root.left = root.right
        root.right = temp

        self.invertTree(root.left)
        self.invertTree(root.right)

        return root
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值