1022.Sum of Root To Leaf Binary Numbers
Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
if(!root) return 0;
if(!root->left && !root->right)
return root->val;
if(root->left) root->left->val +=root->val*2;
if(root->right) root->right->val +=root->val *2;
return sumRootToLeaf(root->left)+sumRootToLeaf(root->right);
}
};Last updated
