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.