Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 226 · DFS Basics

Invert Binary Tree

LeetCode 226 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Swap children at every node.

सोपाTreeDepth-First SearchBreadth-First SearchBinary Tree

मी Invert Binary Tree (LeetCode 226) असा सोडवला — DFS Basics पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Mirroring a tree means swapping every node's left and right children. Do it recursively: invert both subtrees, then swap them.

Approach

  1. 1

    Empty → None.

  2. 2

    Invert left and right subtrees.

  3. 3

    Swap root.left and root.right; return root.

मी कसा सोडवला

Recursive swapPythonO(n) time · O(h) space
# 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 root == None:
                return None
            self.invertTree(root.left)
            self.invertTree(root.right)
            root.left,root.right=root.right,root.left
            return root
स्टेप-थ्रू लोड होत आहे…

Invert Binary Tree — वारंवार विचारले जाणारे प्रश्न

Invert Binary Tree मागील intuition काय आहे?

Mirroring a tree means swapping every node's left and right children. Do it recursively: invert both subtrees, then swap them.

Invert Binary Tree (LeetCode 226) कसा सोडवावा?

1. Empty → None. 2. Invert left and right subtrees. 3. Swap root.left and root.right; return root.

Invert Binary Tree ची time आणि space complexity किती आहे?

Time: O(n). Space: O(h). (Accepted approach: Recursive swap.)

Invert Binary Tree मध्ये सामान्य चुका कोणत्या?

Order doesn't matter — pre-order swapping works too.