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
LeetCode లో తెరవండి ↗

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