题解 | #二叉搜索树的后序遍历序列#

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

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

 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    bool hasPathSum(TreeNode* root, int sum) {
        // write code here
        if(!root)return false;
        int sum1=0;
        return pathSum(root,sum,sum1);
    }
    bool pathSum(TreeNode* root, int sum,int sum1){
        if(!root)return false;
        sum1+=root->val;//局部变量
        cout<<sum1<<endl;//累加和
        if(sum1==sum&&root->left==NULL&&root->right==NULL)return true;
        //找它的左右子树
        return pathSum(root->left, sum, sum1)||
               pathSum(root->right, sum,sum1);
    }
};
全部评论

相关推荐

03-06 18:20
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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