v9.1.1
Menu

Same Tree

easyFREETreesBlind 75

Given two binary trees (level-order arrays), check if they are structurally identical with the same node values.

Example

Input
1,2,3
1,2,3
Output
True
Reasoning
  • Each input line is one binary tree in level order: the root first, then its left and right children, then the next level left to right. Both lines here are 1,2,3.
  • Drawn out, each tree has root 11 with left child 22 and right child 33; both children are leaves.
  • Two trees are the same when every position agrees: a node exists at a position in one tree exactly when it exists there in the other, and the values there are equal.
  • Root: 1=11 = 1. Left of the root: 2=22 = 2. Right of the root: 3=33 = 3. Below the leaves both trees are empty, so no position is filled in one but missing in the other.
  • Every position agrees in shape and value, so the answer is True.
  • Notice that equal values are not enough: root 11 with a left child 22 and root 11 with a right child 22 hold the same values but differ, because an empty position is part of the shape.

Constraints

  • 0 <= number of nodes <= 100
  • -10^4 <= Node.val <= 10^4

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.