本文共 977 字,大约阅读时间需要 3 分钟。
很简单,一遍过。
/** * 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; } return bfs(root, sum, 0); } bool bfs(TreeNode* node, int sum, int curSum){ if(node->left == NULL && node->right == NULL){ return sum == (curSum + node->val); }else{ if (node->left != NULL){ if ( bfs(node->left, sum, curSum + node->val) ){ return true; } } if (node->right != NULL){ if ( bfs(node->right, sum, curSum + node->val) ){ return true; } } } }};
转载地址:http://mcpbb.baihongyu.com/