Same Tree

EasyTrees

Given the roots of two binary trees, p and q, return true if they are the same tree, and false otherwise. Two trees are the same when they have the same shape and every pair of matching nodes holds the same value.

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  p = [5, 1, 9], q = [5, 1, 9]
Output: true

Same shape, same values in the same places.

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

Both hold 5 and 1, but 1 is a left child in one tree and a right child in the other.

Constraints

  • Each tree has 0 to 100 nodes.
  • -10⁴ ≤ node.val ≤ 10⁴

Stuck?

Hint 1

Two trees match when their roots hold the same value, their left subtrees match, and their right subtrees match.

Hint 2

Deal with missing nodes first: both missing is a match, only one missing is not. Then compare the values and recurse on both sides.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur