【问题标题】:solution to "sum root to leaf numbers" problem“总和叶数”问题的解决方案
【发布时间】: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


【解决方案1】:

线

if(!root->left) DFS(root->left, temp, ans); 应该是

if(root->left) DFS(root->left, temp, ans);

对于正确的节点也是如此。基本上,如果一个节点存在,你永远不会在树中往下走。


或者,您可以简化代码:

  • 使用整数而不是字符串来简化计算。
  • 通过复制传递temp 变量,这样您就不必“pop_back”最后一位了。
  • 调用DFS 而不检查指针是否为空,因为它已经在开头进行了检查。
  • 删除最后一个模运算,因为它已经在 DFS 中完成。
void DFS(TreeNode* root, int temp, int *ans){
    if(!root)
        return;

    temp = temp*10 + root->val;

    if(!root->left && !root->right)
        *ans = (*ans + temp)%1003;

    DFS(root->left, temp, ans);
    DFS(root->right, temp, ans);
} 
int Solution::sumNumbers(TreeNode* A) {
    int ans = 0;
    DFS(A, 0, &ans);
    return ans;
}

【讨论】:

  • 在末尾应用模数会导致中间加法溢出的风险。而这种练习通常就是为了做到这一点而设计的。
  • @molbdnilo 是的,你是对的。我会编辑答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
相关资源
最近更新 更多