题解 | #二叉树中是否存在节点和为指定值的路径#
二叉树中是否存在节点和为指定值的路径
http://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
递归
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @param sum int整型 * @return bool布尔型 */ bool hasPathSum(TreeNode* root, int sum) { // write code here target = sum; helper(root, 0); return isExist; } bool isExist = false; int target; void helper(TreeNode* root, int sum){ if(root == NULL) return; //if(sum > target) return; 节点值未必是正数! sum += root -> val; if(root -> left == NULL && root -> right == NULL){ if(sum == target) isExist = true; }else{ if(!isExist) helper(root -> left, sum); if(!isExist) helper(root -> right, sum); } } };