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.