Skip to the code
cf.
+25 XP

#322 Panes Within K Splits

medium

When the user focuses a pane, your editor dims every pane except those exactly k steps away in the layout tree. One step moves from a pane to its parent or to one of its children.

Write panesAtDistance(root, target, k) that returns the ids of all panes exactly k steps from the pane with id target, sorted ascending. Ids are unique and target is always in the tree. If no pane is that far away, return [].

Example 1

Input: root = [1,2,3,4,5,6,7], target = 2, k = 1
Output: [1,4,5]

2's parent is 1 and its children are 4 and 5.

Example 2

Input: root = [1,2,3,4,5,6,7], target = 4, k = 2
Output: [1,5]

From 4, two steps reach 1 (up, up) and 5 (up, down).

Constraints

  • 1 <= number of panes <= 500
  • 0 <= k <= 1000
  • Ids are unique whole numbers.

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).