Matching Phone Menus

Easydepth-first searchAlso known as Same Tree

A clinic runs two phone lines. Callers hear a numbered recording, press 1 or 2, hear the next, and so on until a final message. Each line's menu is therefore a binary tree, where pressing 1 goes left and pressing 2 goes right.

The menus should be copies of each other. After a messy update, the manager wants to know whether they still are, meaning the same recording plays at every step and the same keys lead to the same places.

Your task

Write sameMenu(first, second). Return true if the trees are identical: same shape and same value in every matching position. Otherwise return false.

Two empty trees are identical. Trees are shown in level order, like [7, null, 1], with null for a missing child. Your function receives real TreeNode objects (or null) with val, left and right.

sameMenu(first: TreeNode, second: TreeNode) → bool

Examples

Example 1
Input
first = [4, 2, 6, 1, 3]
second = [4, 2, 6, 1, 3]
Output
true
Why

Both start with 4. Press 1 gives 2 on both, press 2 gives 6 on both, and below 2 the keys lead to 1 and 3 on both.

Example 2
Input
first = [7, 1]
second = [7, null, 1]
Output
false
Why

Both contain 7 and 1, but on the first line you reach 1 by pressing 1, on the second by pressing 2. The menus are different, so the answer is false.

Constraints

  • 0 ≤ number of messages in each menu ≤ 1,000
  • -10,000 ≤ recording number ≤ 10,000
  • Recording numbers may repeat. Each tree is at most 500 levels deep.
Start with brute force

Write each tree out as a list and compare. A plain in-order or pre-order list of values is wrong: [7, 1] and [7, null, 1] both give pre-order 7, 1, yet are different menus. The list must record missing children too, as level order does.

With nulls included it is correct and O(n), but it builds two full lists first. Walking both trees side by side needs no lists and stops at the first difference.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code