Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Same Tree (medium)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

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 met following two conditions:

  1. Both tree are structurally identical.
  2. Each corresponding node on both the trees have the same value.

Example 1:

Given the following two binary trees:

Image

Output: true

Explanation: Both trees are structurally identical and have same values.

Example 2:

Given the following two binary trees:

Image

Output: false

Explanation: Trees are structurally different.

Example 3:

Given the following two binary trees:

Image

Output: false

Explanation: Corresponding nodes have different value ( 4 & 9 ).

Constraints:

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

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible