Skip to the code
cf.
+25 XP

#345 Splits Between Two Panes

medium

Moving keyboard focus in a split-pane layout costs one step per edge of the layout tree. You want to know how many steps it takes to go from one pane to another.

Write stepsBetween(root, a, b) that returns the number of edges on the path between the node with value a and the node with value b. Values are unique and both exist. If a === b, return 0.

Example 1

Input: root = [1,2,3,4,5,6,7], a = 4, b = 5
Output: 2

4 → 2 → 5 uses two edges.

Example 2

Input: root = [1,2,3,4,5,6,7], a = 4, b = 7
Output: 4

4 → 2 → 1 → 3 → 7.

Constraints

  • 1 <= number of nodes <= 10^4
  • All values are unique.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).