题目链接在此
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
.
水题。
把路径以字符串的形式记录下来,然后用std:stoi()转换成int。
class Solution {
public:
int sumNumbers(TreeNode* root) {
if (!root)
return 0;
int sum = 0;
string cur_str = "";
pre_order(root, sum, cur_str);
return sum;
}
private:
void pre_order(TreeNode* root, int& sum, string cur_str) {
if (!root)
return;
cur_str += root->val + '0';
if (!root->left && !root->right) {
sum += stoi(cur_str);
return;
}
pre_order(root->left, sum, cur_str);
pre_order(root->right, sum, cur_str);
}
};
嗯。Leetcode已经刷了整整100题了,然而也就不过总题量的1/5而已。
最近开始看《机器学习实战》。接下来准备把其中的一些笔记整理出来。当然,代码有现成的,所以大多只是把一些语句的注释写出来而已。