Symmetric Tree
LeetCode 101 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Mirror check: outer with outer, inner with inner.
मैंने Symmetric Tree (LeetCode 101) ऐसे हल किया — DFS Basics पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
A tree is symmetric if its left subtree is a mirror of its right. Compare two nodes at a time: their values must match, and the outer pair (left.left, right.right) and inner pair (left.right, right.left) must also be mirrors.
Approach
- 1
dfs(left, right): both None → True; one None → False.
- 2
Values equal, dfs(left.left, right.right), dfs(left.right, right.left).
मैंने कैसे हल किया
Mirror DFSPythonO(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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
def dfs(left,right):
if left==None and right==None:
return True
if left==None or right==None:
return False
return left.val==right.val and dfs(left.left,right.right) and dfs(left.right,right.left)
return dfs(root.left,root.right)Symmetric Tree — अक्सर पूछे जाने वाले प्रश्न
Symmetric Tree के पीछे intuition क्या है?
A tree is symmetric if its left subtree is a mirror of its right. Compare two nodes at a time: their values must match, and the outer pair (left.left, right.right) and inner pair (left.right, right.left) must also be mirrors.
Symmetric Tree (LeetCode 101) कैसे हल करें?
1. dfs(left, right): both None → True; one None → False. 2. Values equal, dfs(left.left, right.right), dfs(left.right, right.left).
Symmetric Tree की time और space complexity क्या है?
Time: O(n)। Space: O(h)। (Accepted approach: Mirror DFS।)
Symmetric Tree में आम गलतियाँ क्या हैं?
Compare cross-wise, not left-with-left.