/100. Same Tree

100. Same Tree

Easy
Trees66.8% acceptance

Given the roots of two binary trees root_a and root_b, determine if the two trees are structurally identical and all corresponding nodes have equal values. Return True if they are identical, otherwise return False.

Example 1

Input: root_a = TreeNode(5, TreeNode(3), TreeNode(7)) root_b = TreeNode(5, TreeNode(3), TreeNode(7))

Output: True

Explanation: Both trees have the same structure and node values.

Example 2

Input: root_a = TreeNode(2, TreeNode(1), None) root_b = TreeNode(2, None, TreeNode(1))

Output: False

Explanation: The structure is different.

Example 3

Input: root_a = None root_b = None

Output: True

Explanation: Both trees are empty.

Constraints

  • The number of nodes in both trees is in the range [0, 100].
  • -10_000 <= TreeNode.val <= 10_000
  • Input trees are binary trees.
  • Input roots may be None (empty tree).
Python (current runtime)

Case 1

Input: root_a = TreeNode(10, TreeNode(20), TreeNode(30)) root_b = TreeNode(10, TreeNode(20), TreeNode(30))

Expected: True

Case 2

Input: root_a = TreeNode(8, TreeNode(4, TreeNode(2)), TreeNode(12)) root_b = TreeNode(8, TreeNode(4), TreeNode(12))

Expected: False

Case 3

Input: root_a = TreeNode(1) root_b = TreeNode(1, TreeNode(2), None)

Expected: False

Case 4

Input: root_a = TreeNode(7, None, TreeNode(9)) root_b = TreeNode(7, None, TreeNode(9))

Expected: True

Case 5

Input: root_a = None root_b = TreeNode(0)

Expected: False