Compute shortest path between tree nodes
SnowflakeSoftware Engineer · OnsiteLast updated
Given a binary tree and two node values u and v, return the shortest path between them as an ordered list of node values. This Snowflake onsite question tests lowest-common-ancestor logic, path reconstruction, iterative vs. recursive implementation, complexity analysis, and preprocessing strategies (parent pointers, binary lifting, Euler tour + RMQ) for answering many queries efficiently.
Question
You are given the root of a binary tree (not necessarily a BST) whose nodes have integer values, and two target values u and v. Implement a function that returns the shortest path between u and v as a list of node values, in order from u to v. If either node does not exist in the tree, return an empty list.
Work through the following:
- Core solution. Return the node-value sequence along the shortest path between
uandv. Achieve O(n) time and O(h) extra space (wherenis the number of nodes andhis the tree height) by finding the lowest common ancestor (LCA) ofuandvand reconstructing the path fromuup to the LCA and then down tov. - Implementations. Provide both an iterative and a recursive implementation, and analyze the time and space complexity of each.
- Multiple queries. Suppose you must answer many
(u, v)path queries on the same tree. Describe preprocessing strategies that speed up repeated queries — e.g. storing parent pointers, Euler tour + Range-Minimum-Query (RMQ) LCA, or binary lifting — and discuss the time/space trade-offs of each (preprocessing cost vs. per-query cost). - Robustness. Explain how your approach handles edge cases: missing nodes, the case
u == v, one node being an ancestor of the other, duplicate values in the tree, and very deep (skewed) trees where recursion may overflow the call stack.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.