LeetCode 112路径总和_子树

 力扣

目录

思路:

1递归


思路:

1递归

递归函数声明:

  bool hasPathSum(TreeNode* root, int targetSum);

递归出口:

如果根节点为空,  返回假

如果只有根节点,  当根节点值为targetsum时返回真,否则返回假

递归体:

考虑左子树和右子树的路径和

递归判断左子树或右子树路径和是否可能为targetsum-root->val

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
//递归出口
if(root==NULL)
return false;
if(!root->left&&!root->right)
{
    return root->val==targetSum;
}
//递归体
return hasPathSum(root->left,targetSum-root->val)||hasPathSum(root->right,targetSum-root->val);
    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.