Tensorum
YouTubeसीखना शुरू करें
LeetCode 100 · DFS Basics

Same Tree

LeetCode 100 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Compare roots and recurse in lockstep.

आसानTreeDepth-First SearchBreadth-First SearchBinary Tree

मैंने 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. 1

    Both None → True; one None → False.

  2. 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.