跳至主要内容

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

Hint

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string getDirections(TreeNode* root, int startValue, int destValue)
{
// Strings to store paths from root to startValue and destValue
// Find paths from root to startValue and destValue

// Initialize directions string
// Length of common path

// Find the length of the common path prefix
while ()
{
}

// Append 'U' (up) moves to go from startValue to the common ancestor
for ()
{
}

// Append moves to go from the common ancestor to destValue
for ()
{
}
// Return the directions
}

// Function to find the path from root to target value and update the path string
bool findPath()
{
// Base case: If root is null, return false
// If the current node's value matches the target, return true indicating target found

// Append 'L' (left) and recursively search in the left subtree
// Backtrack by removing the last character

// Append 'R' (right) and recursively search in the right subtree
// Backtrack by removing the last character

// Return false if target is not found in the subtree
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string getDirections(TreeNode* root, int startValue, int destValue)
{
string startPath, destPath;
findPath(root, startValue, startPath);
findPath(root, destValue, destPath);

string directions;
int commonPath = 0;

while (commonPath < startPath.size() && commonPath < destPath.size() && startPath[commonPath] == destPath[commonPath])
{
commonPath++;
}

for (int i = commonPath; i < startPath.size(); ++i)
{
directions += "U";
}

for (int i = commonPath; i < destPath.size(); ++i)
{
directions += destPath[i];
}
return directions;
}

bool findPath(TreeNode* root, int target, string& path)
{
if (!root) return false;
if (root->val == target) return true;

path += 'L';
if (findPath(root->left, target, path)) return true;
path.pop_back();

path += 'R';
if (findPath(root->right, target, path)) return true;
path.pop_back();

return false;
}
};
  • T: O(n)O(n)
  • S: O(n)O(n)