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.