Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 101 · DFS Basics

Symmetric Tree

LeetCode 101 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Mirror check: outer with outer, inner with inner.

सोपाTreeDepth-First SearchBreadth-First SearchBinary Tree

मी 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. 1

    dfs(left, right): both None → True; one None → False.

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