KatInterview

Navigate Between Nodes in a Recursively Defined Binary Tree

Trees & GraphsModel answer
HardModel answerTrees & Graphsbinary-treesrecursionfibonacci

Last updated

Determine the path between two nodes in a Fibonacci-style binary tree using only their preorder indices, without building the tree in memory.

Problem

A binary tree structure is defined recursively by an order parameter n:

  • When n = 0: the tree contains exactly one node
  • When n = 1: the tree contains exactly one node
  • When n > 1: the tree has a root with left subtree of order n-1 and right subtree of order n-2

Nodes are numbered sequentially starting from 1 using preorder traversal (visit root, then left subtree, then right subtree).

Write a function that takes three inputs:

  • n: the tree order (0 ≤ n ≤ 80)
  • u: the starting node index
  • v: the destination node index

Return a string describing the shortest path from node u to node v using these characters:

  • 'L': move to left child
  • 'R': move to right child
  • 'P': move to parent

Constraints

  • The tree order n can be as large as 80
  • Node indices are 1-based
  • You cannot construct the tree in memory (it may contain over 10^16 nodes)
  • All movements must follow valid parent-child edges

Examples

Example 1:
Input: n = 2, u = 2, v = 3
The tree has structure: root (index 1), left child (index 2), right child (index 3)
Path: go up from 2 to root, then right to 3
Output: "PR"

Example 2:
Input: n = 4, u = 2, v = 9
The tree has 9 nodes total. Node 2 is in the left subtree, node 9 is in the right subtree
Output: "PRR"

Example 3:
Input: n = 3, u = 1, v = 1
Same node
Output: ""

Hints

Hint 1

Calculate how many nodes exist in a tree of order k using the recursive definition. This follows a pattern similar to Fibonacci numbers.

Hint 2

Given a node's index and the current subtree order, you can determine whether it lies in the left subtree, right subtree, or is the root itself by comparing index ranges.

Hint 3

The shortest path between two nodes always passes through their lowest common ancestor. Find where the root-to-node paths diverge.