美文网首页
113.Path Sum II

113.Path Sum II

作者: analanxingde | 来源:发表于2018-10-12 10:36 被阅读7次

题目

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

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来维护相应的path路径,与112题目的DFS问题思路类似,分四步处理。
注意的是:
1)这个回溯过程path的维护每次返回之前无论这条路符不符合要求都需要删除当前节点进行回溯。
2)helper函数为了维护同一个path和res,形参是引用
3)helper函数无论是否找到路径最终倒要返回,即回溯四步处理中保证第二步第四步都可以返回。

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

相关文章

网友评论

      本文标题:113.Path Sum II

      本文链接:https://www.haomeiwen.com/subject/oujwaftx.html