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.

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]
]

与Path Sum相比,本题是求出路径,所以,在找到满足的路径之后,不能直接返回,而是将其添加到一个vector<vector<int>>中。在查找的过程中,每经过一个结点,先使用一个vector<int>将该路径中的所有结点记录下来。由于vector<vector<int>>是用来记录所有满足的路径的,所以传递引用给它是为了对它的每一个改动都是对其本身的操作,而不是对其副本的操作,使用来返回找到的所有路径。使用的vector<int>只是拷贝操作,所以都是对其副本的操作,不会对原始的vector<int>有影响。

 

C++代码实现:

#include<iostream>
#include<new>
#include<vector>
using namespace std;

//Definition for binary tree
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> > path;
        vector<int> tmp;
        hasPathSum(root,sum,path,tmp);
        return path;
    }
    void hasPathSum(TreeNode *root, int sum,vector<vector<int> > &path,vector<int> tmp)
    {
        if(root==NULL)
            return;
        tmp.push_back(root->val);
        if(root->left==NULL&&root->right==NULL&&(sum-root->val)==0)
        {
            path.push_back(tmp);
        }
        if(root->left)
            hasPathSum(root->left,sum-root->val,path,tmp);
        if(root->right)
            hasPathSum(root->right,sum-root->val,path,tmp);
    }
    void createTree(TreeNode *&root)
    {
        int i;
        cin>>i;
        if(i!=0)
        {
            root=new TreeNode(i);
            if(root==NULL)
                return;
            createTree(root->left);
            createTree(root->right);
        }
    }
};
int main()
{
    Solution s;
    TreeNode *root;
    s.createTree(root);
    vector<vector<int> > path=s.pathSum(root,6);
    for(auto a:path)
    {
        for(auto v:a)
            cout<<v<<" ";
        cout<<endl;
    }
}

运行结果:

 
posted @ 2014-11-16 09:43  Jessica程序猿  阅读(215)  评论(0编辑  收藏  举报