[Leetcode][Tree][Path Sum I & II]
很简单的一道题,判断和为sum的路径是否存在。
结果WA了两次,一次是由于没有考虑清楚深搜停止的条件,另外一次是由于没有考虑到Path必须是从root到leaf的。
1 /** 2 * Definition for binary tree 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 bool hasPathSum(TreeNode *root, int sum) { 13 if (root == NULL) { 14 return false; 15 } else { 16 if (sum == root->val && root->left == NULL && root->right == NULL) { 17 return true; 18 } 19 sum -= root->val; 20 return hasPathSum(root->left, sum) || hasPathSum(root->right, sum); 21 } 22 } 23 };
第一次遇到跟题解写的思路一模一样的情况,但是题解还是比我写的更精简,更高效,减少了root==null时候的调用。
1 /** 2 * Definition for binary tree 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 bool hasPathSum(TreeNode *root, int sum) { 13 if (root == NULL) { 14 return false; 15 } else { 16 if (root->left == NULL && root->right == NULL) { 17 return sum == root->val; 18 } 19 sum -= root->val; 20 return hasPathSum(root->left, sum) || hasPathSum(root->right, sum); 21 } 22 } 23 };
另外一个题Path Sum 2
就是把结果保存下来罢了,常见做法。
1 /** 2 * Definition for binary tree 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 res.clear(); 14 vector<int> tmp; 15 dfs(root, sum, tmp); 16 return res; 17 } 18 private: 19 vector<vector<int> > res; 20 void dfs(TreeNode * root, int sum, vector<int> tmp) { 21 if (root == NULL) { 22 return; 23 } 24 tmp.push_back(root->val); 25 sum -= root->val; 26 if (root->left == NULL && root->right == NULL && sum == 0) { 27 res.push_back(tmp); 28 } 29 dfs(root->left, sum, tmp); 30 dfs(root->right, sum, tmp); 31 } 32 };
看了一下题解, 有一个非常关键的地方,我调用的vector参数没有用引用&,会造成空间复杂度非常大,应该避免这种做法。
1 /** 2 * Definition for binary tree 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 res.clear(); 14 vector<int> tmp; 15 dfs(root, sum, tmp); 16 return res; 17 } 18 private: 19 vector<vector<int> > res; 20 void dfs(TreeNode * root, int sum, vector<int>& tmp) { 21 if (root == NULL) { 22 return; 23 } 24 tmp.push_back(root->val); 25 sum -= root->val; 26 if (root->left == NULL && root->right == NULL && sum == 0) { 27 res.push_back(tmp); 28 } 29 dfs(root->left, sum, tmp); 30 dfs(root->right, sum, tmp); 31 tmp.pop_back(); 32 } 33 };