Step-By-Step Directions From a Binary Tree Node to Another

Medium · Trees · String · Tree · Depth-First Search · Binary Tree

Problem

You are given the root of a binary tree with n nodes whose values are exactly 1 to n, each used once, and two different values startValue and destValue.

Describe the shortest path from the start node to the destination node as a string of moves:

Return that string.

Examples

Input: root = [4,1,6,3,None,2,5], startValue = 3, destValue = 5
Output: "UURR"

Climb from 3 to 1 to 4, then go right to 6 and right again to 5.

Input: root = [1,2], startValue = 1, destValue = 2
Output: "L"

The destination is the start's left child.

Input: root = [5,1,2,3,None,6,4], startValue = 4, destValue = 5
Output: "UU"

4 is the right child of 2, which is the right child of 5: two steps up.

Constraints

Approaches

Follow-up

The route is unique: a tree has exactly one simple path between two nodes, so there is only one shortest move string. For many queries on the same tree, store each node's depth and use binary lifting to find common ancestors in O(log n) per query.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…