Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Root to node path

Solution

Code

bool getPath(vector<int>& res, TreeNode<int>* root, int x)
{
    if (!root)
        return false;
    res.push_back(root->data);
    if (root->data == x)
        return true;
    if (getPath(res, root->left, x) || getPath(res, root->right, x))
        return true;
    res.pop_back();
    return false;
}

vector<int> pathInATree(TreeNode<int>* root, int x)
{
    vector<int> res;
    if (!root)
        return res;
    getPath(res, root, x);
    return res;
}