leetcode129Sum Root to Leaf Numbers
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
.
一言以蔽之,请使用递归。分别在先将本层的节点的值域放入string中,然后,当进入最深处的子节点时,将string放入vector。然后在返回自己这层的时候,去掉自己这层节点的值域,以此往复,最后遍历结果数组,atoi转成int型相加即可,具体内容见代码,有问题可以详细探讨。。。我之前写的很多题目中都有类似的递归方式,,,所以我这次很快就有思路,并且迅速的写出来了。现在觉得这类的算法题目真的很简单。。。
/** * 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: void function(TreeNode * root, vector<string> & str, string & temp) { if (root->left == NULL && root->right == NULL) { temp += '0' + root->val; str.push_back(temp); temp = temp.substr(0, temp.size() - 1); return ; } temp += '0' + root->val; if (root->left) { function(root->left, str, temp); } if (root->right) { function(root->right, str, temp); } temp = temp.substr(0, temp.size() - 1); } int sumNumbers(TreeNode* root) { if (root == NULL) return 0; vector<string> str; string temp; function(root, str, temp); //str.erase(unique(str.begin(), str.end()), str.end()); int sum = 0; for (vector<string>::iterator it = str.begin(); it != str.end(); ++it) { sum += atoi((*it).c_str()); } return sum; } };