LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2096. Step-By-Step Directions From a Binary Tree Node to Another

Description

You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t.

Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction:

  • 'L' means to go from a node to its left child node.
  • 'R' means to go from a node to its right child node.
  • 'U' means to go from a node to its parent node.

Return the step-by-step directions of the shortest path from node s to node t.

 

Example 1:

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.

Example 2:

Input: root = [2,1], startValue = 2, destValue = 1
Output: "L"
Explanation: The shortest path is: 2 → 1.

 

Constraints:

  • The number of nodes in the tree is n.
  • 2 <= n <= 105
  • 1 <= Node.val <= n
  • All the values in the tree are unique.
  • 1 <= startValue, destValue <= n
  • startValue != destValue

Solutions

Solution 1: Lowest Common Ancestor + DFS

We can first find the lowest common ancestor of nodes startValue and destValue, denoted as node. Then, starting from node, we find the paths to startValue and destValue respectively. The path from startValue to node will consist of a number of Us, and the path from node to destValue will be the path. Finally, we concatenate these two paths.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.

PythonJavaC++GoTypeScriptJavaScript
# 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)(code-box)

Solution 2: Lowest Common Ancestor + DFS (Optimized)

We can start from root, find the paths to startValue and destValue, denoted as pathToStart and pathToDest, respectively. Then, remove the longest common prefix of pathToStart and pathToDest. At this point, the length of pathToStart is the number of Us in the answer, and the path of pathToDest is the path in the answer. We just need to concatenate these two paths.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.

PythonJavaC++GoTypeScriptJavaScript
# 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 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 path_to_start = [] path_to_dest = [] dfs(root, startValue, path_to_start) dfs(root, destValue, path_to_dest) i = 0 while ( i < len(path_to_start) and i < len(path_to_dest) and path_to_start[i] == path_to_dest[i] ): i += 1 return "U" * (len(path_to_start) - i) + "".join(path_to_dest[i:])(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !