题解 | #递归方式——二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//递归形式
#include <cstddef>
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(root == NULL) return 0;
//叶子节点的定义即左右孩子为空,并且当前叶子节点的值等于上一层传递进来的sum值
if(root->left == NULL && root->right == NULL && root->val - sum == 0) return true;
//递归根节点的左孩子和右孩子
return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right ,sum-root->val);
}
};
查看15道真题和解析