LeetCode113. Path Sum II 找出二叉树中总值为sum的所有路径 #算法# 第十一周

2022-06-23 11:25:03 浏览数 (1)

原题如下

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,

代码语言:javascript复制
      5
     / 
    4   8
   /   / 
  11  13  4
 /      / 
7    2  5   1

Return:

代码语言:javascript复制
[
   [5,4,11,2],
   [5,8,4,5]
]

思路

是上一篇博客 LeetCode112. Path Sum 的升级版,用同样的递归思想,只不过这次要从左右子树接收路径数组,并在每一条可行路径前插入根节点的值,以形成一条最终完整的路径。

代码

代码语言:javascript复制
/**
 * 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;
    }
};

0 人点赞