[Leetcode] #113 Path Sum II

来源:互联网 发布:微信网络错误 编辑:程序博客网 时间:2024/06/03 15:51

Discription:

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]]

Solution:

采用DFS,给出两种稍微不同的递归写法。

写法一:

void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res){path.push_back(root->val);sum -= root->val;if (sum == 0 && !root->left && !root->right)res.push_back(path);if (root->left)pathSum(root->left, sum, path, res);if (root->right)pathSum(root->right, sum, path, res);path.pop_back();}vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> ans;if (!root) return ans;vector<int> path;pathSum(root, sum, path, ans);return ans;}

写法二:

void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res){if (!root) return;path.push_back(root->val);sum -= root->val;if (sum == 0 && !root->left && !root->right)res.push_back(path);pathSum(root->left, sum, path, res);pathSum(root->right, sum, path, res);path.pop_back();}vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> ans;vector<int> path;pathSum(root, sum, path, ans);return ans;}

0 0
原创粉丝点击