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

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary tree whose n nodes hold the distinct values 1 to n, plus two different values startValue and destValue. Describe the shortest route from the node holding startValue to the node holding destValue as a string of moves: - 'L' means go from a node to its left child, - 'R' means go from a node to its right child, - 'U' means go from a node to its parent. The shortest route in a tree is unique, so exactly one string is correct.

Examples

Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
Output: "UURL"
From 3 go up to 1, up to 5, right to 2, then left to 6.
Input: root = [2,1], startValue = 2, destValue = 1
Output: "L"
1 is the left child of 2.

Constraints

  • 2 <= n <= 10^5
  • 1 <= Node.val <= n
  • All values are distinct
  • `startValue != destValue`, and both appear in the tree

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems