LeetCode Week3

113. Path Sum II

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,

在这里插入图片描述

solution:

本题意是从根节点到叶子节点找出所有相加之和等于sum的路径,并存在一条路径为一维数组。解决的方法和之前的I差不多,都是递归遍历左右节点。每次递归都减去相应节点的值,每次递归前将此节点的值存进vector容器内。当到达叶子节点时,如果sum值等于叶子节点的值,则这条路径满足条件,将这条路径即path添加到新的一个vector容器内paths。

/**
 * 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:
    void pathSum(vector<vector<int> > &paths, vector<int> &path, TreeNode *tree, int sum)
    {
        if(!tree) return;
        path.push_back(tree->val);
        if(!tree->left && !tree->right && tree->val==sum)
            paths.push_back(path);
        if(tree->left)
        {
            pathSum(paths,path,tree->left,sum-tree->val);
            path.pop_back();
        }
        if(tree->right)
        {
            pathSum(paths,path,tree->right,sum-tree->val);
            path.pop_back();
        }
    }
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > paths;
        vector<int> path;
        pathSum(paths,path,root,sum);
        return paths;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Xiouzai_/article/details/82765396