LeetCode 226. Invert Binary Tree

Post by ailswan Nov.05, 2023

226. Invert Binary Tree

Problem Statement

link: https://leetcode.com/problems/invert-binary-tree/ https://leetcode.cn/problems/invert-binary-tree/

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

Example:

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

Input: root = [] Output: 0

Input: root = [1] Output: 1

Solution Approach

recursion

Algorithm

divided and conquer

Implement

    class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
      if root:
          root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
      return root