↓Skip to main content
  1. LeetCode/

LeetCode 101: Symmetric Tree

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-02

  • Submissions: Runtime Error ×2 → Accepted → Wrong Answer → Accepted ×4

Approach
#

Symmetric means the left subtree mirrors the right. Write a function checking whether two trees mirror each other (Tree Template 1): equal values, with a.left mirroring b.right (outer) and a.right mirroring b.left (inner).

My Attempts
#

The first two versions had syntax errors; a later one wrote left == right, comparing node objects instead of values, so two distinct nodes were never equal: [3, 3, 3] should be True but returned False.

Solution
#

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def mirror(a, b):
            if not a or not b:
                return a is b
            return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)
        return mirror(root.left, root.right)

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • Compare a.val == b.val; a == b checks whether they are the same object.

Interview Explanation
#

I write a mirror check: equal values, with outer pairs and inner pairs mirroring too, then apply it to the root’s two subtrees. Time O(n).

Related

LeetCode 100: Same Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 note: two empty trees are equal, one empty and one not differ, and otherwise compare values and recurse on both sides
LeetCode 104: Maximum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 104 note: depth is 1 plus the larger subtree depth, with 0 for an empty tree
LeetCode 144: Binary Tree Preorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 note: iterative pre-order traversal records on pop and pushes the right child before the left so the left is handled first
LeetCode 94: Binary Tree Inorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 94 note: iterative in-order traversal, pushing nodes while going left, recording on pop, then turning to the right subtree
LeetCode 83: Remove Duplicates from Sorted List
·2 mins
LeetCode Easy Linked-List
LeetCode 83 note: sorted, so duplicates are adjacent; skip cur.next while it equals cur, and advance only otherwise
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer