Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
思路:自底向上递归(类似于二叉树最大路径和 Binary Tree Max Path Sum)。每个内部节点会处在数条root-to-leaf的路径上,一个内部节点会有不同的power,这个内部节点的power是左子树和右子树的power乘以10。叶子节点的power是1。
代码如下:
int sumNumbers(TreeNode *root) { int sum = 0; vector<int> power; sumNumbersUtil(root, power, sum); return sum; } void sumNumbersUtil(TreeNode* root, vector<int>& power, int& sum) {// utility function // sum: the sum up until now // power: the vector of powers of the root node if(root==NULL) return; vector<int>power1, power2; sumNumbersUtil(root->left, power1, sum); sumNumbersUtil(root->right, power2, sum); // combine the powers of left and right subtree if(power1.size()>0) { for(int i=0; i<power1.size(); i++) power.push_back(10*power1[i]); } if(power2.size()>0) { for(int i=0; i<power2.size(); i++) power.push_back(10*power2[i]); } // root is a leaf node if(power1.size()==0 && power2.size()==0) power.push_back(1); for(int i=0; i<power.size(); i++) { sum = sum + root->val * power[i]; } }