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 .
Hide TagsTree Depth-first Search
Idea: Typical DFS deep search
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution {Private: intm_sum; Vector<int>M_vec; intIntvec2int (vector<int>nums) { intnum =0; for(inti =0; I < nums.size (); i++) {num= num *Ten+Nums[i]; } returnnum; } voidDFS (treenode*root) { if(Root = =NULL)return; M_vec.push_back (Root-val); if(Root->left = = NULL && Root->right = =NULL) {M_sum+=Intvec2int (M_vec); M_vec.pop_back (); return; } if(root->Left ) Dfs (root-Left ); if(root->Right ) Dfs (root-Right ); M_vec.pop_back (); } Public: intSumnumbers (TreeNode *root) {m_vec.clear (); M_sum=0; DFS (root); returnm_sum; }};
[Leetcode] Sum Root to Leaf Numbers