Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Check if Two Trees are Identical

Medium Acceptance 76.59% Points 30.00

You are given the roots of two binary trees. Your task is to determine whether the two trees are identical.

Two binary trees are considered identical if:

  • They have the same structure.
  • Their corresponding nodes contain the same values.

Return true if both trees are identical; otherwise, return false.

Examples
Example 1

image Input: root1 = [1,2,3], root2 = [1,2,3]
Output: true
Explanation: Both binary trees have the same structure and matching node values.

Example 2

image Input: root1 = [1,2], root2 = [1,null,2]
Output: false
Explanation: The structures of the two binary trees are different.

Example 3

image Input: root1 = [1,2,1], root2 = [1,1,2]
Output: false
Explanation: The corresponding node values are different, even though both trees contain the same number of nodes.

Constraints
    • 0 = Number of nodes in each tree = 105
    • -10? = Node.data = 10?
Companies
Apple Samsung
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions