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.