Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 226 · DFS Basics

Invert Binary Tree

LeetCode 226 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Swap children at every node.

సులభంTreeDepth-First SearchBreadth-First SearchBinary Tree
LeetCode లో తెరవండి ↗

నేను 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.