Same Tree

Given the roots of two binary trees p and q, return true if the two trees are structurally identical and the nodes have the same values. Otherwise return false. Pattern focus: Trust Recursion. Use a clean recursive check on both structure and value.

Input Format

p = first binary tree root, q = second binary tree root

Output Format

true if the trees are identical, otherwise false

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^4 <= node values <= 10^4
  • Input must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

p = [1,2,3]
q = [1,2,3]

Output:

true

Explanation:

Both trees have the same structure and values.

Example 2:

Input:

p = [1,2]
q = [1,null,2]

Output:

false

Explanation:

The structure differs, so the trees are not identical.

Loading...
Same Tree - Binary Tree DSA Problem