题解 | 二叉树中和为某一值的路径(一) 注意值传递与引用传递

二叉树中和为某一值的路径(一)

https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    bool hasPathSum(TreeNode* root, int sum) {
        // write code here
        return readpath(root,sum);

    }
    /*
    bool readpath(TreeNode* root,int sum){
        if(root==nullptr)return false;
        if(sum-=root->val==0)return true;//   实际执行顺序:root->val == 0 先算,结果再赋给 sum
        return readpath(root->left,sum)||readpath(root->right,sum);
    }
    */
    bool readpath(TreeNode* root,int sum){
        if(root==nullptr)return false;
        sum-=root->val;
        if(root->left==nullptr&&root->right==nullptr&&sum==0)return true;
        return readpath(root->left, sum)||readpath(root->right, sum);
    }//这里代码能跑通的原因是sum是值传递。每次递归调用,sum 都是新的局部变量,互不影响
    /*等价于
    // 显式计算,不修改sum
    bool readpath(TreeNode* root, int sum) {
        if(!root) return false;
        
        int newSum = sum - root->val;  // 新建变量,不改动sum
        
        if(!root->left && !root->right) return newSum == 0;
        
        return readpath(root->left, newSum) || 
           readpath(root->right, newSum);  // 传newSum,原sum不变
}
    */
    
    
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务