【发布时间】:2019-05-21 12:54:54
【问题描述】:
给定一棵仅包含 0-9 数字的二叉树,每个从根到叶的路径都可以表示一个数字。
一个例子是从根到叶的路径 1->2->3,它代表数字 123。
求所有从根到叶数的总和 % 1003。
示例:
如果 1 是根,那么它的左孩子是 2,右孩子是 3,那么,
从根到叶的路径 1->2 代表数字 12。
从根到叶的路径 1->3 代表数字 13。
返回总和 = (12 + 13) % 1003 = 25 % 1003 = 25。
原问题is here
P.S:这不是家庭作业,我正在为大学实习做准备。
我的尝试:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void DFS(TreeNode* root, string &temp, int *ans){
if(!root)
return;
temp = temp + to_string(root->val);
if(root->left == NULL && root->right == NULL && temp.length()!=0){
*ans = (*ans + stoi(temp))%1003;
}
if(!root->left)
DFS(root->left, temp, ans);
if(!root->right)
DFS(root->right, temp, ans);
if(!temp.empty())
temp.pop_back();
}
int Solution::sumNumbers(TreeNode* A) {
string temp = "";
int ans = 0;
DFS(A, temp, &ans);
return ans%1003;
}
【问题讨论】:
-
那么问题是什么?
-
解决方法不正确。它总是返回 0
-
我同意这个问题不清楚,很难回答。我假设代码没有按预期工作。鉴于此,我可以在
if(!root->left) DFS(root->left, temp, ans);行中看到一些奇怪的东西。不应该是if(root->left) DFS(root->left, temp, ans);吗?正确的节点也是如此。基本上,如果一个节点存在,你永远不会在树中向下走。 -
天哪,我真不敢相信我这么傻。谢谢它完成了。
-
而且你不需要一个字符串来累积数字,只需乘以 10 并添加新数字。
标签: c++ binary-tree