Facebook PixelSame Tree — Coding Practice
Same TreeEasy

Same Tree

Easy 9.2k62% acceptance
TreeDepth-First SearchBinary Tree

Given the roots of two binary trees p and q, return true if the trees are structurally identical and every pair of corresponding nodes holds the same value, and false otherwise.

Each tree is given in level-order (TreeNode with { val, left, right }, null for a missing child).

Example 1
Input: p = [1,2,3], q = [1,2,3]
Output: true
Same shape and same values at every position.
Example 2
Input: p = [1,2], q = [1,null,2]
Output: false
One tree has a left child where the other has a right child.
Example 3
Input: p = [1,2,1], q = [1,1,2]
Output: false
Constraints
  • The number of nodes in each tree is in the range [0, 100].
  • -10⁴ ≤ Node.val ≤ 10⁴
Asked atAmazonGoogleMicrosoftBloomberg
JavaScript
Loading editor…
Case 1
[1,2,3], [1,2,3]
expected: true
Case 2
[1,2], [1,null,2]
expected: false
Case 3
[1,2,1], [1,1,2]
expected: false
Case 4
[], []
expected: true
Case 5
[1], []
expected: false
Case 6
[1,2,3,4,5], [1,2,3,4,5]
expected: true
Case 7
[5,4,8,11,null,13,4], [5,4,8,11,null,13,4]
expected: true