Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
    For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
    Return the sum of these numbers.

    Example 1:
    1022. Sum of Root To Leaf Binary Numbers - 图1
    Input: [1,0,1,0,1,0,1]
    Output: 22
    Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

    Note:

    1. The number of nodes in the tree is between 1 and 1000.
    2. node.val is 0 or 1.
    3. The answer will not exceed 2^31 - 1.

    Runtime: 8 ms, faster than 60.81% of C++ online submissions for Sum of Root To Leaf Binary Numbers.
    Memory Usage: 16.7 MB, less than 100.00% of C++ online submissions for Sum of Root To Leaf Binary Numbers.

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. int sumRootToLeaf(TreeNode* root) {
    15. int sum = 0;
    16. traverse(root, sum, root->val);
    17. return sum;
    18. }
    19. void traverse(TreeNode* root, int& sum, int lastSum) {
    20. if (root->left != NULL) {
    21. traverse(root->left, sum, lastSum * 2 + root->left->val);
    22. }
    23. if (root->right != NULL) {
    24. traverse(root->right, sum, lastSum * 2 + root->right->val);
    25. }
    26. if (root->left == NULL && root->right == NULL) {
    27. sum += lastSum;
    28. }
    29. }
    30. };