LeetCode:. 112 Total Path Sum path (C language)

Description Title:
Given a binary tree and a destination and determines whether the root node to the leaf node in the tree path exists, all the nodes on this route, and equal to the target value is added.

Description: leaf node is a node has no child nodes.

Example:
Given the following binary tree, and the target and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

Returns true, because the presence of the target path and the root node to the leaf node 22 5-> 4-> 11-> 2.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/path-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
answer:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


bool func(struct TreeNode* root, int cur, int sum)
{
    if(NULL == root) return false;
    
    cur = cur + root->val;
    
    if(NULL == root->left && NULL == root->right)
    {
        if(sum == cur) return true;
    }

    return func(root->left, cur, sum) || func(root->right, cur, sum);
}

bool hasPathSum(struct TreeNode* root, int sum)
{   
    int cur = 0;
    return func(root,cur,sum);
}

operation result:

Here Insert Picture Description

Published 157 original articles · won praise 119 · views 260 000 +

Guess you like

Origin blog.csdn.net/wangqingchuan92/article/details/104779571