Same Tree Problem Solving Tutorial: A Complete Comparison of 3 Solutions | LeetCode 100 Best Practice

Same Tree Problem Solving Tutorial Diagram | LeetCode 100

This article provides a complete breakdown of the solution to LeetCode 100 Same Tree: from the problem-solving approach and algorithm steps to time and space complexity, and it also summarizes boundary cases and compares three solutions to help you understand Same Tree from scratch.

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

 

Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false

 

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -10 4 <= Node.val <= 10 4

Python

				
					# time complexity: O(n) # space complexity: O(n) from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: if p == None and q == None: return True if p == None or q == None: return False if p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) p = TreeNode(1) p.left = TreeNode(2) p.right = TreeNode(2) q = TreeNode(1) q.left = TreeNode(2) q.right = TreeNode(2) print(Solution().isSameTree(p, q))
				
			

Same Tree Problem Solving Approach

Determining whether two trees are identical is the purest form of structural recursion: simultaneously visit both trees and compare three things at each position—whether both sides are empty, whether the values are the same, and whether the left and right subtrees are also the same. As long as the termination condition is clearly stated, the main body only needs one line.

Same Tree Algorithm Steps

  1. If both p and q are null, return true.
  2. If one of them is null (and the other is not), return false.
  3. If p.val is not equal to q.val, return false.
  4. Returns the logical AND of isSameTree(p.left, q.left) and isSameTree(p.right, q.right).

Same Tree Complexity Analysis

projectComplexity
Time complexityO(n)
Space complexityO(h)

The algorithm visits all nodes of at most two trees once, with a time complexity of O(n), where n is the number of nodes in the smaller tree (returning early because they are different). The space complexity is O(h) with a recursion depth, and the worst-case time complexity is O(n).

Boundary cases and common errors of Same Tree

  • If both trees are empty, you must return true.
  • Both cases with the same structure but different values, and cases with the same value but different structures, should be correctly judged as false.
  • Returning early can significantly reduce the number of actual visits.
  • When using iteration, the node pairings of the two trees must be pushed in simultaneously; they cannot be visited separately.

Comparison of other solutions for Same Tree

solutiontimespaceillustrate
Compare the serialized strings.O(n)O(n)It's feasible, but null values need to be handled; a null flag should be used to avoid ambiguity.
BFS (Browse-First Search) layer-by-layer comparisonO(n)O(n)Requires standing in a row, space is relatively large
Synchronous recursive comparisonO(n)O(h)This article adopts