leetcode 112. 路径总和 c++

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/glw0223/article/details/88729370

112. 路径总和

分析

  • 找到一个就可以结束
  • 二叉树还是递归用的多
  • 深度优先遍历
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (root == nullptr){
            return false;
        }
        if (root->left == nullptr and root->right == nullptr){
             return sum == root->val;
        }
        bool b1=hasPathSum(root->left, sum - root->val);
        if(b1){
            return true;
        }
        bool b2=hasPathSum(root->right, sum - root->val);
        if(b2){
            return true;
        }
        return false;
    }
};

感谢:https://github.com/glw0223/Leetcode-1/blob/master/src/0112-Path-Sum/0112.cpp

猜你喜欢

转载自blog.csdn.net/glw0223/article/details/88729370
今日推荐