[LeetCode] 路径和 Path Sum

来源:互联网 发布:js声明二维数组 编辑:程序博客网 时间:2024/05/17 02:21

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]]
思路:从上往下递归,递归的过程中保存每个节点的值,并且从sum里减去该节点的值,将新的sum向下传递。递归到叶子节点的时候,如果叶子节点和sum相等,那么所经过的路径就是一个符合要求的路径。(为了把所有符合要求的路径聚集在一起,下面的算法用了一个按引用传递的变量 vector<vector<int>>& paths).代码如下:

    vector<vector<int> > pathSum(TreeNode *root, int sum) {        // main function        vector<vector<int>> paths;        vector<int> path;        hasPathSumUtil(root, sum, path, paths );                return paths;    }        bool hasPathSumUtil(TreeNode *root, int sum, vector<int> path, vector<vector<int>>& paths ) {        // utility function                if(root==NULL) return false;                path.push_back(root->val); // store the nodes along each path                if(root->left==NULL && root->right==NULL) // if we reach a leaf node            if(root->val == sum)            {                paths.push_back(path); // we have find a valid path                return true;            }            else                return false; // this path is not valid                        bool leftHas = hasPathSumUtil(root->left, sum - root->val, path, paths);        bool rightHas = hasPathSumUtil(root->right, sum - root->val, path, paths);        if(leftHas || rightHas)            return true;        else            return false;    }



0 0
原创粉丝点击