Binary Tree Path

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are: ["1->2->5", "1->3"]

Solution: Recursive

vector<string> binaryTreePaths(TreeNode* root) {
    if (!root) return {};

    vector<string> res;
    backtrack(root, "", res);
    return res;
}

void backtrack(TreeNode* root, string s, vector<string>& res) {
    if (!root) return;

    if (!root->left && !root->right) {
        s += to_string(root->val);
        res.push_back(s);
        return;
    }

    s += to_string(root->val) + "->";
    backtrack(root->left, s, res);
    backtrack(root->right, s, res);
}

Solution: Recursive

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if (root) helper(root, "", res);
        return res;
    }

    void helper(TreeNode* node, string out, vector<string>& res) {
        if (!node->left && !node->right) res.push_back(out + to_string(node->val));

        if (node->left) helper(node->left, out + to_string(node->val) + "->", res);
        if (node->right) helper(node->right, out + to_string(node->val) + "->", res);
    }

results matching ""

    No results matching ""