题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#include <limits>
class Solution {
public:
/**
* vector<int> tree;
vector<int> preorderTraversal(TreeNode* root) {
// write code here
if(root==nullptr){
return tree;
}
tree.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return tree;
}
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
int num = 0;
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(!root){
return false;
}
if(root&&root->val == sum && root->right == nullptr && root->left == nullptr){
return true;
}
return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}
};

