↓Skip to main content
  1. LeetCode/

LeetCode 100: Same 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: Wrong Answer → Accepted → Wrong Answer → Accepted → Wrong Answer → Accepted → Wrong Answer → Runtime Error → Accepted → Wrong Answer → Runtime Error → Wrong Answer → Accepted ×4

Approach
#

Three cases (Tree Template 1):

  • Both empty: equal.
  • Exactly one empty: different.
  • Both present: equal values and equal left and right subtrees.

My Attempts
#

The failing versions all mishandled empty trees: returning nothing (None) or False for two empty trees, or True when only one was empty, e.g. [1] and [].

Solution
#

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p or not q:
            return p is q                           # 兩個都是 None 才相同
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Complexity
#

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

Mistakes to Avoid
#

  • Two empty trees return True; do not leave that path without a return.
  • One empty and one not is False.

Interview Explanation
#

I handle empty trees first: equal only if both are empty. Otherwise I compare the values and recurse on both subtrees. Time O(n).

Related

LeetCode 101: Symmetric Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 note: the left and right subtrees must mirror each other, outer with outer and inner with inner; compare values, not node objects
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