Invert Binary Tree
LeetCode 226 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Swap children at every node.
నేను 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
Empty → None.
- 2
Invert left and right subtrees.
- 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 rootInvert 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.