Ctrl K

Identical Trees

Easy
You are given the roots of two binary trees, first and second. Check whether they are the same tree. Two trees are the same when they have the same shape (matching nodes have children on exactly the same sides) and matching nodes hold equal values. Two empty trees count as the same. Return True if the trees are identical, and False otherwise.
Example 1
first=tree_node([6, 2, 8, None, 4]), second=tree_node([6, 2, 8, None, 4]) → True

Shape and values match at every node.

Example 2
first=tree_node([6, 2, 8]), second=tree_node([6, 8, 2]) → False

The shape is the same, but 2 and 8 sit on opposite sides of the root.

Example 3
first=tree_node([5, 5]), second=tree_node([5, None, 5]) → False

The values are the same, but in the second tree the child is on the right, not the left.

Constraints
  • Each tree has between 0 and 100 nodes
  • -10^4 ≤ Node.val ≤ 10^4
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMirror-Image Tree EasyTree Height EasyNearest Leaf Depth EasyLeaf Path With a Given Total EasyMirror the Tree Easy
loading Python…
Input
first=tree_node([6, 2, 8, None, 4]), second=tree_node([6, 2, 8, None, 4])
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 135 tests on the server, hidden ones included.