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 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 = + = 25 .
Idea: Recently slept badly, made the brain also short-circuited. have been thinking about how to get the number from the leaf node upward. A great effort to the AC, the results of a look at the answer, immediately depressed. It will be done in less than 10 lines.
The specific principle is the depth first, in the downward iteration of the process, with a variable to keep the parent node above the number passed down, return when the results add up.
Public intsumnumbers (TreeNode root) {returnHelper (Root,0);} Public intHelper (TreeNode root,intcursum) { if(Root = =NULL)return 0; Cursum= cursum*Ten+Root.val; if(Root.left = =NULL&& Root.right = =NULL)returncursum; returnHelper (Root.left, cursum) +Helper (root.right, cursum);}
Here is my own AC code, super Long, super cumbersome, as a negative example. The idea is to put each number inside a vector. It's tedious because I'm just trying to get back.
intSumnumbers (TreeNode *root) { intS, e, sum =0; Vector<vector<int>>v; Numbers (Root, S, E, V); for(vector<vector<int>>::iterator it = V.begin (); It! = V.end (); ++it) { intnum =0; while(!it->empty ()) {num= num *Ten+ it->Back (); It-Pop_back (); } Sum+=num; } returnsum; } voidNumbers (TreeNode * root,int&s,int&e, vector<vector<int>>&v) {intSL =-1, El =-1, sr =-1, er =-1; S= e =-1; if(Root = NULL)return; if(Root->left = = NULL && Root->right = = null)//The new number is pressed into the leaf node{e= s =v.size (); V.push_back (Vector<int> (1,root->val)); return; } if(Root->left! =NULL) {Numbers (Root-Left , SL, El, v); for(inti = SL; I <= el; ++i) {v[i].push_back (root-val); } s= SL; E =el; } if(Root->right! =NULL) {Numbers (Root-Right , sr, er, v); for(inti = SR; I <= er; ++i) {v[i].push_back (root-val); } s= (S = =-1) ?sr:s; E=er; } }
"Leetcode" Sum Root to Leaf Numbers (hard)