题解 | #二叉树中和为某一值的路径(一)#

二叉树中和为某一值的路径(一)

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);
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务