题解 | #二叉树中和为某一值的路径(一)#递归实现
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <cstddef>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool flag = false; //是否成功找到路径
bool hasPathSum(TreeNode* root, int sum) {
// write code here
findPath(root,sum,0); //调用递归函数
return flag ;
}
void findPath(TreeNode* root, int sum, int count) { //当前节点 要求的路径值 当前路径值
//特殊情况判断
if(root==NULL){
return;
}
if(flag){
return;
}
//递归出口 路径长度为sum,并且时叶子节点
if( (count+root->val) == sum && root->left==NULL && root->right==NULL ){
flag = true; //成功找到路径
return;
}
if(root->left){ //遍历左孩子
findPath(root->left, sum, count + root->val);
}
if(root->right){ //遍历右孩子
findPath(root->right,sum, count + root->val);
}
}
};


查看21道真题和解析