---
# System prepended metadata

title: Leetcode 1022. Sum of Root To Leaf Binary Numbers
tags: [Leetcode(C++)]

---

# Leetcode 1022. Sum of Root To Leaf Binary Numbers
###### tags: `Leetcode(C++)`

題目 : https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 。

想法 : 

    pre_order走訪並計算由根到葉子的二進位總和。

時間複雜度 : O(n)。

程式碼 :

```
/**
 * 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 {
public:
    
    void solve(TreeNode *root, string str, int &ans){
        if(root == nullptr) return;
        
        str+=to_string(root->val);
        if(root->left == nullptr && root->right == nullptr){
            int sum=0, l=str.size();
            //cout << str << endl;
            for(int i=0 ; i<l ; i++){
                sum=sum*2+(str[i]-'0');
            }
            //cout << sum << endl;
            ans+=sum;
            str.pop_back();
            
            return;
        }
        
        solve(root->left, str, ans);
        solve(root->right, str, ans);
    }
    
    int sumRootToLeaf(TreeNode* root) {
        int sum=0;
        solve(root, "", sum);
        return sum;
    }
};
```