Check if two trees are identical or not

Binary Trees Medium Problems Medium

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