Skip to content

Latest commit

 

History

History
executable file
·
95 lines (49 loc) · 3.34 KB

112. Path Sum.md

File metadata and controls

executable file
·
95 lines (49 loc) · 3.34 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

##(一)题目

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example: Given the below binary tree and sum = 22, 5 /
4 8 / /
11 13 4 / \
7 2 1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

##(二)解题

题目大意:给定一个二叉树和一个整数,求二叉树是否存在一个根节点到叶子节点的路径,使得该路径上的所有节点的值加起来等于该整数。

解题思路:递归,碰到叶子节点就算路径上的节点值的和,判断等不等于该整数。

/**

 * Definition for a binary tree node.

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    bool hasPathSum(TreeNode* root, int sum) {

        if(root==NULL) return false;//树为空返回false

        bool flag = false;

        dfsTree(root,sum,0,flag);//递归函数

        return flag;

    }

    //sum为要求的路径和


    //cur为当前路径和


    //flag为是否满足cur==sum


    void dfsTree(TreeNode* root, int& sum,int cur,bool& flag)

    {

        if(root->left == NULL && root->right==NULL) if(!flag) flag=(sum==(cur+root->val));//此时为叶子节点,判断路径和等不等于sum

        if(root->left!=NULL) dfsTree(root->left,sum,cur+root->val,flag);//往左子树搜索

        if(root->right!=NULL) dfsTree(root->right,sum,cur+root->val,flag);//往右子树搜索

    }

};