Path Sum && II
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.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool hasPathSum(struct TreeNode* root, int sum) { bool left, right; if(root == NULL) return false; else if(root->val == sum && root->left == NULL && root->right == NULL) return true; else { left = hasPathSum(root->left, sum - root->val); right = hasPathSum(root->right, sum - root->val); return (left || right); } }
- 关于DFS
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> pathSum(TreeNode* root, int sum) { 13 vector<vector<int>> result; 14 vector<int> bkup; 15 int index = 0; // index of result 16 int addSum = 0; 17 // go over the tree, keep a addSum, 18 // if addSum > sum, return 19 DFS(sum, root, bkup, addSum, result, index); 20 return result; 21 } 22 private: 23 void DFS(int sum, TreeNode* node, vector<int> bkup, int addSum, vector<vector<int>> &result, int &index){ 24 if(node == NULL) 25 return; 26 bkup.push_back(node->val); 27 addSum += node->val; 28 if (addSum == sum && node->left == NULL & node->right == NULL) { 29 result.push_back(bkup); 30 } 31 else { 32 DFS(sum, node->left, bkup, addSum, result, index); 33 DFS(sum, node->right, bkup, addSum, result, index); 34 } 35 return; 36 } 37 };
- 主要是C++中vector的使用,直接push_back