leetcode-cpp 112.路径总和

112.路径总和

  • 题目:

在这里插入图片描述

  • 链接

    leetcode

  • solution:

    这个跟前面那个输出路径的很像,其实都是一个套路,DFS,递归到叶子节点就判断是不是一样,一样就置res为true。

    ps:看了眼评论区 好像就我写的最蠢,但是很好理解吗~

  • code


class Solution {
public:
    bool res=false;
    bool hasPathSum(TreeNode* root, int sum) {
        DFS(root,0,sum);
        return res;
    }
    void DFS(TreeNode* root,int cal,int sum){
        if(!root) return;
        cal+=root->val;
        if(!root->left&&!root->right) 
        {
            if(cal==sum) res=true;
        }
        DFS(root->left,cal,sum);
        DFS(root->right,cal,sum);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43255713/article/details/105524652