本文主要是介绍LeetCode113. Path Sum II 找出二叉树中总值为sum的所有路径 #算法# 第十一周,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原题如下
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
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]
]
思路
是上一篇博客 LeetCode112. Path Sum 的升级版,用同样的递归思想,只不过这次要从左右子树接收路径数组,并在每一条可行路径前插入根节点的值,以形成一条最终完整的路径。
代码
/*** 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>> paths;if(root == NULL) return paths;if(root->left == NULL && root->right == NULL){if(root->val == sum){vector<int> path;path.push_back(root->val);paths.push_back(path);return paths;}}vector<vector<int>> leftPaths = pathSum(root->left, sum - root->val);vector<vector<int>> rightPaths = pathSum(root->right, sum - root->val);// 向所有路径的头部加入根节点的值for(int i = 0; i < leftPaths.size(); i++)leftPaths[i].insert(leftPaths[i].cbegin(), root->val);for(int i = 0; i < rightPaths.size(); i++)rightPaths[i].insert(rightPaths[i].cbegin(), root->val);// 合并所有路径leftPaths.insert(leftPaths.cend(), rightPaths.cbegin(), rightPaths.cend());return leftPaths;}
};
这篇关于LeetCode113. Path Sum II 找出二叉树中总值为sum的所有路径 #算法# 第十一周的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!