Path Sum II

来源:互联网 发布:淘宝网折800唯影女装 编辑:程序博客网 时间:2024/06/06 12:36
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]

]

思路:题目的要求是给一棵二叉树,还有一个给定数值,让找到从根节点到叶子节点的所有路径,在此路径上节点值的和等于给定数值。

解决方法:做一个helper的函数递归处理

(1)对于第一层的根节点来说,求的是根到叶子节点路径和为sum

(2)对于第二层的节点来说,求得是根到叶子节点和为sum-root->val

(3)当访问到有符合条件的叶子节点答案的时候,处理完成后再继续处理别的时候注意从vector中删除当前的叶子节点的数据

(4)对于非叶子节点,在slo中压入当前的值表示这个节点下的子树在处理,如果遍历完以这个节点为根的子树后需要在slo中删除这个节点的数据,再继续处理别的节点。

/** * 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<int>slo;        vector<vector<int>>res;        if(root)              helper(root,slo,res,sum);        return res;    }        void helper(TreeNode*root,vector<int>&slo,vector<vector<int>>&res,int sum)    {        if(!root)            return;        if(root->left==NULL&&root->right==NULL&&root->val==sum)        {            slo.push_back(root->val);            res.push_back(slo);            slo.pop_back();        }        else        {            slo.push_back(root->val);            if(root->left)                helper(root->left,slo,res,sum-root->val);            if(root->right)                helper(root->right,slo,res,sum-root->val);            slo.pop_back();        }    }    };


0 0
原创粉丝点击