【LeetCode】112. Path Sum
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.
For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
Solution 1
1 class Solution { 2 public: 3 bool hasPathSum(TreeNode* root, int sum) { 4 if (!root) 5 return false; 6 if (!root->left && !root->right && root->val == sum) 7 return true; 8 return hasPathSum(root->left, sum - root->val) 9 || hasPathSum(root->right, sum - root->val); 10 } 11 };
Solution 2
1 class Solution { 2 public: 3 bool hasPathSum(TreeNode* root, int sum) { 4 if (!root) 5 return false; 6 queue<TreeNode*> que; 7 que.push(root); 8 queue<int> qsum; 9 qsum.push(root->val); 10 11 while (!que.empty()) { 12 TreeNode* cur = que.front(); 13 que.pop(); 14 int num = qsum.front(); 15 qsum.pop(); 16 17 if (!cur->left && !cur->right && num == sum) { 18 return true; 19 } 20 if (cur->left) { 21 que.push(cur->left); 22 qsum.push(cur->left->val + num); 23 } 24 if (cur->right) { 25 que.push(cur->right); 26 qsum.push(cur->right->val + num); 27 } 28 } 29 return false; 30 } 31 };