题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
#include <stdbool.h>
bool hasPathSum(struct TreeNode* root, int sum ) {
// write code here
if(root==NULL) return false; //二叉树为空
if(root->val == sum && root->left == NULL && root->right == NULL) return true; //当前节点的值等于sum且当前节点是叶子节点
else {
bool lh = false,rh = false;
lh = hasPathSum(root->left, sum - root->val); // 减去当前节点值,在当前节点左子树中继续寻找
rh = hasPathSum(root->right, sum - root->val);// 减去当前节点值,在当前节点右子树中继续寻找
return (lh|rh);
}
}
查看12道真题和解析