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

/**
 * 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)