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; } } };
时间: 2024-10-28 13:40:16