Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 100 · DFS Basics

Same Tree

LeetCode 100 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Compare roots and recurse in lockstep.

సులభంTreeDepth-First SearchBreadth-First SearchBinary Tree
LeetCode లో తెరవండి ↗

నేను 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.