leetcode--Path Sum II

1.题目描述

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

2.解法分析

深度搜索即可,用一个变量记录curVec当前路径,一旦获得满足条件的路径,记录到最终结果中。

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        result.clear();
        if(!root)return result;   
        int curSum = sum;
        vector<int> curVec;
        myPathSum(root,curSum,curVec);    
        return result;   
    }
    
    void myPathSum(TreeNode *root,int &curSum,vector<int> & curVec)
    {
        curVec.push_back(root->val);
        curSum-=root->val;
        
        if(!root->left&&!root->right)
        {
            if(curSum==0)
            {
                result.push_back(curVec);
            }
            return ;
        }
        
        if(root->left){
            myPathSum(root->left,curSum,curVec);
            curSum+=root->left->val;curVec.pop_back();
        }
        if(root->right){
            myPathSum(root->right,curSum,curVec);
            curSum+=root->right->val;curVec.pop_back();
        }  
    }
    
    private:
        vector<vector<int>> result;
};
posted @ 2013-08-13 20:29  曾见绝美的阳光  阅读(203)  评论(0编辑  收藏  举报