leetcode 113. Path Sum II
- Path Sum II:题目链接
dfs +huisu
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
class Solution { public: void dfs(TreeNode* root, int sum, vector<int>& curPath, vector<vector<int>>& allPath) { if (root == NULL) { return; } if (root->left == NULL && root->right == NULL) { if (root->val == sum) { curPath.push_back(root->val); allPath.push_back(curPath); return; } } curPath.push_back(root->val); if (root->left != NULL) { dfs(root->left, sum - root->val,curPath,allPath); curPath.pop_back(); } if (root->right != NULL) { dfs(root->right, sum - root->val,curPath,allPath); curPath.pop_back(); } } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> allPath ; vector<int> curPath; dfs(root, sum, curPath, allPath); return allPath; } };
|
递归解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) { return res; } if (root.left == null && root.right == null && root.val == sum) { List<Integer> list = new ArrayList<>(); list.add(root.val); res.add(list); } List<List<Integer>> leftRes = pathSum(root.left, sum - root.val); for (List list : leftRes) { list.add(0,root.val); res.add(list); } List<List<Integer>> rightRes = pathSum(root.right, sum - root.val); for (List list : rightRes) { list.add(0,root.val); res.add(list); } return res; } }
|