leetcode 112. Path Sum 、 113. Path Sum II 、437. Path Sum III
112. Path Sum
自己的一个错误写法:
class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root == NULL) return false; int value = 0; return hasPathSum(root,sum,value); } bool hasPathSum(TreeNode* root,int sum,int value){ if(root == NULL){ if(value == sum) return true; else return false; } bool left = hasPathSum(root->left,sum,value + root->val); bool right = hasPathSum(root->right,sum,value + root->val); return left || right; } }; Input: [1,2] 1 Output: true Expected: false
只有左右节点都为NULL时才是叶子节点,所以这个代码在例子[1,2],1的右节点时就判断错误了,这个右节点虽然sum满足条件,但他本身不是叶子节点
正确写法:
class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root == NULL) return false; if(!root->left && !root->right && root->val == sum) return true; return hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum - root->val); } };
113. Path Sum II
class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> result; vector<int> res; pathSum(root,sum,result,res); return result; } void pathSum(TreeNode* root,int sum,vector<vector<int>>& result,vector<int>& res){ if(root == NULL) return; res.push_back(root->val); if(!root->left && !root->right && root->val == sum) result.push_back(res); pathSum(root->left,sum - root->val,result,res); pathSum(root->right,sum - root->val,result,res); res.pop_back(); } };
第二种写法:
/** * 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: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> result; vector<int> res; pathSum(root,sum,res,result); return result; } void pathSum(TreeNode* root,int sum,vector<int> res,vector<vector<int>>& result){ if(root == NULL) return; if(!root->left && !root->right && root->val == sum){ res.push_back(root->val); result.push_back(res); } res.push_back(root->val); pathSum(root->left,sum - root->val,res,result); pathSum(root->right,sum - root->val,res,result); return; } };
437. Path Sum III
注意:
1. i只能到size-1,如果到size,就是把所有的和都减掉,相当于没有任何节点相加
2. 不能写成if(curSum == sum)
else{
减去res中之前的数
}
因为即使是当前位置到根节点满足情况,也有可能当前位置到根下面的节点也满足情况
class Solution { public: int pathSum(TreeNode* root, int sum) { vector<int> res; int num = 0; int curSum = 0; pathSum(root,sum,curSum,res,num); return num; } void pathSum(TreeNode* root,int sum,int curSum,vector<int>& res,int& num){ if(root == NULL) return; curSum += root->val; if(curSum == sum) num++; res.push_back(root->val); int t = curSum; for(int i = 0;i < res.size() - 1;i++){ t -= res[i]; if(t == sum) num++; } pathSum(root->left,sum,curSum,res,num); pathSum(root->right,sum,curSum,res,num); res.pop_back(); } };