Leetcode 2096: Step-By-Step Directions From a Binary Tree Node to Another

grid47
grid47
Exploring patterns and algorithms
Apr 11, 2024 7 min read

You are given a binary tree where each node has a unique value between 1 and n. You are also given a start node and a destination node, each represented by their values. Your task is to find the shortest path from the start node to the destination node in terms of directions. The directions should be represented by a string using the characters ‘L’, ‘R’, and ‘U’, where ‘L’ means left child, ‘R’ means right child, and ‘U’ means moving to the parent node.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of the binary tree and two integers representing the start and destination nodes.
Example: root = [8, 3, 10, 1, 6, null, 14, null, null, 4, 7], startValue = 1, destValue = 7
Constraints:
• The number of nodes in the tree is between 2 and 10^5.
• Each node's value is unique.
• The startValue and destValue are different.
Output: Return a string representing the directions from the start node to the destination node, using 'L', 'R', and 'U' characters.
Example: Output: 'UUR'
Constraints:
Goal: The goal is to find the shortest path between the start and destination nodes in terms of directions.
Steps:
• First, find the path from the root to the start node and the path from the root to the destination node.
• Compare the two paths and remove the common part from the end of both paths.
• For the remaining part of the start path, replace each step with 'U' to move upwards to the common ancestor.
• For the remaining part of the destination path, leave the steps as they are, which will be moving downwards to the destination.
Goal: The problem constraints ensure that the binary tree is large enough to test the efficiency of the solution, and the start and destination nodes are distinct.
Steps:
• The binary tree contains between 2 and 10^5 nodes.
• All node values are unique.
• startValue != destValue.
Assumptions:
• The tree is not empty.
• Both startValue and destValue are valid and exist in the tree.
Input: Example 1: root = [8, 3, 10, 1, 6, null, 14, null, null, 4, 7], startValue = 1, destValue = 7
Explanation: The shortest path from 1 to 7 is: 1 → 3 → 6 → 7. The directions are 'UUR'.

Input: Example 2: root = [1, 2], startValue = 1, destValue = 2
Explanation: The shortest path from 1 to 2 is directly down the left child. The direction is 'L'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus