1. String Path Building + Integer Conversion
Intuition
Recursively build string path. When reaching a leaf, convert string to integer and add to total sum.
When to apply: Basic baseline check.
Algorithm
- Step 1: Helper dfs(node, strPath, total).
- Step 2: If leaf, total += stoi(strPath + to_string(node.val)).
- Step 3: Recurse left and right with strPath + to_string(node.val).
- Step 4: Return total.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution { int total = 0; void dfs(TreeNode* node, string s) { if (!node) return; s += to_string(node->val); if (!node->left && !node->right) { total += stoi(s); return; } dfs(node->left, s); dfs(node->right, s); }public: int sumNumbers(TreeNode* root) { dfs(root, ""); return total; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n * h)— String copying takes O(h) per node. - Space complexity:
O(h)— String path takes O(h) memory.