Check if two trees are identical or not

Binary Trees Medium Problems Medium
  • Fun Fact: The given problem is fundamentally used in various applications such as code compilers and database systems where we need to compare two Abstract Syntax Trees (ASTs)
  • It's also used in code similarity checkers and plagiarism detection software where they need to analyze if two codes perform the same operations
  • In Data Science and ML applications, this concept is helpful in measuring the similarities between decision trees

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 are structurally identical, and the nodes have the same value.

Examples:

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

Output : true

Explanation : Both trees images are shown below



Input : p = [1, 2, 1] , q = [1, 1, 2]

Output : false

Explanation : Both trees images are shown below



Input : p = [5, 1, 2, 8, null, null, 5, null, 4, null, null, 7 ], q = [5, 1, 2, 8, null, null, 4, null, 5, null, null, 7 ]

Constraints

  • 1 <= Number of Nodes <= 100
  • -104 <= Node.val <= 104

Hints

  • An iterative DFS approach can be implemented using a stack to simulate recursion. Each time we pop a node pair (p, q), we compare their values and push their left and right children back onto the stack for further comparison.

Company Tags

Teladoc Health Deloitte Wayfair Siemens Healthineers Broadcom Optum PayPal Chewy Rakuten McKinsey & Company Activision Blizzard Rockstar Games Snowflake Western Digital AMD Swiggy Epic Games Etsy Target Electronic Arts DoorDash NVIDIA Boston Consulting Group Robinhood Riot Games Google Microsoft Amazon Meta Apple Netflix Adobe