Topic:
Given a binary tree containing digits from only 0-9 , each root-to-leaf path could represent a number.
an example is the root-to-leaf path 1->2->3 which represents the Number
Find The total sum of all root-to-leaf numbers.
For example,
1 / 2 3
The Root-to-leaf Path1->2Represents the number12.
The Root-to-leaf Path1->3Represents the number13.
Return the sum = + = 25 .
Idea: If you know the number on the path from the root node to all the leaf nodes, and then convert the path to an integer, add all the integer of the path conversion, which is the result of the request.
void Helper_leaf (bintree* root,vector<int>& path,int& sum) {if (root = NULL) return;p ath.push_back (root- >value); if (root->left = = NULL && Root->right = = null) {int tmp=0;for (int i=0;i<path.size (); i++) tmp = tmp*10 + path[i];sum + = tmp;//cout<< "tmp is" <<tmp<<endl; return;} Helper_leaf (root->left,path,sum); Helper_leaf (root->right,path,sum);p ath.pop_back ();} int roottoleaf (bintree* root) {if (root = NULL) return 0;vector<int> path;int sum=0;helper_leaf (root,path,sum); return sum;}
Sum Root to Leaf Numbers--leetcode