1. BFS with Queue Storing Node & Path
Intuition
Push root and to_string(root->val) into a queue. For each popped node, if it is a leaf, push its path string to the answer. Otherwise, append children and updated paths to queue.
When to apply: When avoiding recursion is required.
Algorithm
- Step 1: If root == null return [].
- Step 2: Queue stores pairs (node, pathString). Push (root, String(root.val)).
- Step 3: Pop (curr, path). If curr has no children, add path to result.
- Step 4: If curr.left != null, enqueue (curr.left, path +
->+ curr.left.val). - Step 5: If curr.right != null, enqueue (curr.right, path +
->+ curr.right.val).
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { if (!root) return {}; vector<string> res; queue<pair<TreeNode*, string>> q; q.push({root, to_string(root->val)}); while (!q.empty()) { auto [node, path] = q.front(); q.pop(); if (!node->left && !node->right) { res.push_back(path); } if (node->left) q.push({node->left, path + "->" + to_string(node->left->val)}); if (node->right) q.push({node->right, path + "->" + to_string(node->right->val)}); } return res; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n * h)— Copying strings of length up to h for each node. - Space complexity:
O(n * h)— Queue holds pairs of nodes and string paths.