2096. Step-By-Step Directions From a Binary Tree Node to Another #31
-
You are given the Find the shortest path starting from node
Return the step-by-step directions of the shortest path from node s to node t. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2096. Step-By-Step Directions From a Binary Tree Node to Another <?PHP
/**
* Definition for a binary tree node.
*/
class TreeNode {
public $val;
public $left;
public $right;
public function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
class Solution {
/**
* @param TreeNode $root
* @param Integer $startValue
* @param Integer $destValue
* @return String
*/
function getDirections($root, $startValue, $destValue) {
$startPath = [];
$destPath = [];
$this->findPath($root, $startValue, $startPath);
$this->findPath($root, $destValue, $destPath);
// Find the common path length
$i = 0;
while ($i < count($startPath) && $i < count($destPath) && $startPath[$i] === $destPath[$i]) {
$i++;
}
// Directions from startValue to LCA
$upMoves = count($startPath) - $i;
$downMoves = array_slice($destPath, $i);
// Combine paths
return str_repeat('U', $upMoves) . implode('', $downMoves);
}
/**
* @param $root
* @param $value
* @param $path
* @return bool
*/
function findPath($root, $value, &$path) {
if ($root === null) {
return false;
}
if ($root->val === $value) {
return true;
}
$path[] = 'L';
if (self::findPath($root->left, $value, $path)) {
return true;
}
array_pop($path);
$path[] = 'R';
if (self::findPath($root->right, $value, $path)) {
return true;
}
array_pop($path);
return false;
}
}
// Example usage:
$root = new TreeNode(5);
$root->left = new TreeNode(1);
$root->right = new TreeNode(2);
$root->left->left = new TreeNode(3);
$root->right->left = new TreeNode(6);
$root->right->right = new TreeNode(4);
$startValue = 3;
$destValue = 6;
echo getDirections($root, $startValue, $destValue); // Outputs: "UURL"
$root2 = new TreeNode(5);
$root2->left = new TreeNode(1);
$root2->right = new TreeNode(2);
$root2->left->left = new TreeNode(3);
$root2->right->left = new TreeNode(6);
$root2->right->right = new TreeNode(4);
$startValue2 = 3;
$destValue2 = 6;
echo getDirections($root2, $startValue2, $destValue2); // Outputs: "L"
?> Explanation:
Contact Links If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me! If you want more helpful content like this, feel free to follow me: |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2096. Step-By-Step Directions From a…