Posted on

Description

Submission

/**
 * 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 {
    int lcaDepth, startDepth;
    TreeNode* lcaNode = nullptr;
    string halfPath;
    int lca(TreeNode* root, int startValue, int destValue, int depth) {
        if(!root) return 0;
        int count = lca(root->left, startValue, destValue, depth+1) + lca(root->right, startValue, destValue, depth+1) + (root->val == startValue || root->val == destValue);
        if(count == 2 && lcaNode == nullptr) {
            lcaNode = root;
            lcaDepth = depth;
        }
        if(root->val == startValue) startDepth =  depth;
        return count;
    }

    bool dfs(TreeNode* node, int destValue, string& path) {

        if(!node) return false;

        if(node->val == destValue) return true;

        path.push_back('L');
        if(dfs(node->left, destValue, path)) return true;
        path.pop_back();

        path.push_back('R');
        if(dfs(node->right, destValue, path)) return true;
        path.pop_back();
        return false;
    }
public:
    string getDirections(TreeNode* root, int startValue, int destValue) {
        lca(root, startValue, destValue, 0);

        string ret = "";

        for(int i = 0; i < startDepth - lcaDepth; ++i) {
            ret.push_back('U');
        }

        dfs(lcaNode, destValue, ret);
        
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *