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.