[leetcode] Path Sum
2014-07-17 20:47
363 查看
解法一:
解法二:
/** * 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; if(root->left==NULL&&root->right==NULL) return sum==root->val; return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val); } };
解法二:
/** * 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,int curSum){ if(root==NULL) return false; curSum+=root->val; if(root->left==NULL&&root->right==NULL) return sum==curSum; return hasPathSum(root->left,sum,curSum)||hasPathSum(root->right,sum,curSum); } bool hasPathSum(TreeNode *root, int sum) { return hasPathSum(root,sum,0); } };
相关文章推荐
- [leetcode]112. Path Sum
- [LeetCode116]Path Sum
- LeetCode - Path Sum
- Path Sum 【leetcode】
- Leetcode---Path Sum
- Leetcode 64. Minimum Path Sum (Medium) (cpp)
- LeetCode-Path Sum
- LeetCode --- 64. Minimum Path Sum
- 【leetcode】64. Minimum Path Sum
- [LeetCode] Path Sum
- LeetCode:Path Sum
- [leetcode]64. Minimum Path Sum
- LeetCode112——Path Sum
- LeetCode--Path Sum
- Leetcode - Dynamic Progr - 64. Minimum Path Sum(BFS+DP)
- Leetcode解题笔记 64. Minimum Path Sum [Medium] 动态规划
- leetcode112 Path Sum
- 【LeetCode】 112. Path Sum
- [LeetCode]64.Minimum Path Sum
- Leetcode: Path Sum