剑指offer - 面试题34: 二叉树中和为某一值的路径 - C++

看了剑指offer写出的答案:

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>> result;
        if(root == nullptr) return result;
        vector<int> path;
        int currentSum = 0;
        FindPathCore(root, expectNumber, path, currentSum, result);
        return result;
    }
     
    void FindPathCore(TreeNode* root, int expectNumber,
                 vector<int>& path, int currentSum,
                 vector<vector<int>>& result) {
         
        currentSum += root->val;
        path.push_back(root->val);
         
        bool isLeaf = root->left == nullptr && root->right == nullptr;
        if(isLeaf) {
            if (currentSum == expectNumber) {
                result.push_back(path);
            }
        } else {
            if(root->left != nullptr) {
                FindPathCore(root->left, expectNumber, path, currentSum, result);
            }
            if(root->right != nullptr) {
                FindPathCore(root->right, expectNumber, path, currentSum, result);
            }
        }
        path.pop_back();
    }
};

此题难点在于记录路径,解决方案:用一个vector<int> path 记录路径。难点在于处理完当前节点后,递归调用左右节点后,要把path中当前节点弹出。所有函数公用path。因为刚开始不懂,跟着代码走一遍之后明白了这步的意义。另外currentSum就不用去减了,因为传的是值而不是引用。

做完之后我不甘心地去讨论区逛了逛,发现一种更简练的写法:

class Solution {
    vector<vector<int> > result;
    vector<int> path;
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root == nullptr) return result;
        
        path.push_back(root->val);
        bool isLeaf = root->left == nullptr && root->right == nullptr;
        if(isLeaf) {
            if(root->val == expectNumber) {
                result.push_back(path);
            }
        } else {
            if(root->left != nullptr) {
                FindPath(root->left, expectNumber - root->val);
            }
            if(root->right != nullptr) {
                FindPath(root->right, expectNumber - root->val);
            }
        }
        path.pop_back();
        return result;
    }
};

将需要共用的变量作为类的变量,省去增加引用类型的参数。

expectNumber也是当前节点所需要的路径和,我刚开始看到这道题也是觉得应该边向下走边减去,这样更符合递归的思想。简化了参数,可以直接调用自身递归,不用再写一个函数。

只有直接调用的函数返回return有效,中间调用的函数的return不予理睬。

妙哉!

另外,牛客网题目上说要按数组长度先大后小输出,我不知道该咋做,索性提交后它也没检测这个~

猜你喜欢

转载自blog.csdn.net/L_bic/article/details/88061186