【问题标题】:find all the nodes of a binary tree from **root to leaf** which gives the sum equal to the target sum找到从**根到叶**的二叉树的所有节点,其总和等于目标总和
【发布时间】:2019-11-12 16:38:25
【问题描述】:

给定一棵二叉树,找到从根到叶的所有节点,当添加时等于目标总和。 该算法在 python 中使用时运行良好,但当我使用 c++ 时,它会引发错误。

错误:在第 22 行字符 80 处无效使用 void 表达式:

       help(root->left, sum - root->val, temp.push_back(root->val), result); 

这是我的代码。

    void help(TreeNode* root, int sum, vector<int>& temp, vector<vector<int>>& result)
    {
        if ((sum == root->val) and (not root->left and not root->right))
        {
            temp.push_back(root->val);
            result.push_back(temp);
            return;
        }

        if (root->left){
            help(root->left, sum - root->val, temp.push_back(root->val), result);
        }      // here i'm getting an error.

        if (root->right){
            help(root->right, sum - root->val, temp.push_back(root->val), result);
        }
    }

    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        if (root == NULL)
           return;
        vector<vector<int>> result;
        vector<int> temp;
        help(root, sum, temp, result);
        return result;
    }

我不明白如何解决此错误?

【问题讨论】:

标签: c++ binary-tree


【解决方案1】:

代码temp.push_back(root-&gt;val) 返回void,函数help 需要vector

你应该将代码分成如下两行:

if (root->left) {
    temp.push_back(root->val);
    help(root->left, sum - root->val, temp, result);
}    

if (root->right) {
    temp.push_back(root->val);
    help(root->right, sum - root->val, temp, result);
}

【讨论】:

    【解决方案2】:

    您的编译器错误是由于终止递归调用的边界条件不完善,而不是由于突出显示的代码。

    比较器运算符需要在您的代码中进行更正。此外,如果当前总和已经大于目标总和,您可以通过停止进一步搜索来提高代码效率。

    void help(TreeNode* root, int sum, vector<int>& temp, vector<vector<int>>& result)
    {
            if ( sum == root->val &&  !root->left && !root->right )
            {
                temp.push_back(root->val);
                result.push_back(temp);
                return;
            }
            /* other codes*/
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 2016-08-03
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多