Same Tree
LeetCode 100 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Compare roots and recurse in lockstep.
मी Same Tree (LeetCode 100) असा सोडवला — DFS Basics पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Two trees are the same if their roots match and their left subtrees are the same and their right subtrees are the same. Two empty trees are equal; one empty and one not are different.
Approach
- 1
Both None → True; one None → False.
- 2
Values equal and both subtree pairs equal.
मी कसा सोडवला
Parallel 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def dfs(node1,node2):
if node1==None and node2==None:
return True
if node1==None or node2==None:
return False
return node1.val==node2.val and dfs(node1.left,node2.left) and dfs(node1.right,node2.right)
return dfs(p,q)Same Tree — वारंवार विचारले जाणारे प्रश्न
Same Tree मागील intuition काय आहे?
Two trees are the same if their roots match and their left subtrees are the same and their right subtrees are the same. Two empty trees are equal; one empty and one not are different.
Same Tree (LeetCode 100) कसा सोडवावा?
1. Both None → True; one None → False. 2. Values equal and both subtree pairs equal.
Same Tree ची time आणि space complexity किती आहे?
Time: O(n). Space: O(h). (Accepted approach: Parallel DFS.)
Same Tree मध्ये सामान्य चुका कोणत्या?
Check the None cases before reading .val.