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.