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

 

 

Hide Tags
 Tree Depth-first Search
 

思路:dfs,递归,注意标红的语句

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    vector<vector<int> > m_res;
    vector<int>  m_vec;
    public:
        void dfs(TreeNode * root, int sum)
        {
            if(root == NULL)
                return;
            if(root->left == NULL && root->right == NULL)
            {   
                if(root->val == sum)
                {   
                    m_vec.push_back(root->val);
                    m_res.push_back(m_vec);
                    m_vec.pop_back();
                }   
                return;
            }   

            m_vec.push_back(root->val);
            if(root->left)
            {   
                dfs(root->left, sum-root->val);
            }   
            if(root->right)
            {
                dfs(root->right, sum-root->val);
            }
            m_vec.pop_back();
        }

        vector<vector<int> > pathSum(TreeNode *root, int sum)
        {
            m_vec.clear();
            m_res.clear();

            dfs(root, sum);
            return m_res;
        }
};

 

posted @ 2015-04-10 14:05  穆穆兔兔  阅读(182)  评论(0编辑  收藏  举报