leetcode_num112_Path Sum

来源:互联网 发布:mac重新启动后卡住了 编辑:程序博客网 时间:2024/05/27 21:11

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.

/** * Definition for binary tree * 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;        int y;        y=root->val;        if ((root->left==NULL) and (root->right==NULL)){            if (y==sum)                return true;            else                 return false;            }        else{            int z;            z=sum-y;            bool check,check1,check2;            check1=hasPathSum(root->left,z);            check2=hasPathSum(root->right,z);            check= (check1 or check2);            return check;        }    }};


0 0
原创粉丝点击