Step-By-Step Directions From a Binary Tree Node to Another — LeetCode 2096 Python Solution

MediumTreeDepth-First SearchStringBinary Tree
Problem
#2096
Reading time
8 min

The problem

You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n.

Example

Input
root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
Output
"UURL"
Explanation
The shortest path is: 3 → 1 → 5 → 2 → 6.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right


class Solution:
    def getDirections(
        self, root: Optional[TreeNode], startValue: int, destValue: int
    ) -> str:
        def lca(node: Optional[TreeNode], p: int, q: int):
            if node is None or node.val in (p, q):
                return node
            left = lca(node.left, p, q)
            right = lca(node.right, p, q)
            if left and right:
                return node
            return left or right

        def dfs(node: Optional[TreeNode], x: int, path: List[str]):
            if node is None:
                return False
            if node.val == x:
                return True
            path.append("L")
            if dfs(node.left, x, path):
                return True
            path[-1] = "R"
            if dfs(node.right, x, path):
                return True
            path.pop()
            return False

        node = lca(root, startValue, destValue)

        path_to_start = []
        path_to_dest = []

        dfs(node, startValue, path_to_start)
        dfs(node, destValue, path_to_dest)

        return "U" * len(path_to_start) + "".join(path_to_dest)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another?
LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another is rated Medium on LeetCode.
What is the time complexity of LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another cover?
LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another is tagged Tree, Depth-First Search, String and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview