LeetCode-----第113题-----路径总和 II

路径总和 II

难度:中等

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

题目分析:

      在上一题的基础上,加一个路径的存储,这里用的是回溯法,需要退步

      结束条件:root == null

      all station:就是一个前序遍历,符合条件的就压入res,但是压入后,不要直接返回,因为这个不是结束条件,根左右需要遍历完。

扫描二维码关注公众号,回复: 11493525 查看本文章

参考代码:

/**
 * 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;
        if(root == NULL)
            return res;
        
        vector<int> temp;
        find_depth(root,res,temp,sum);
        return res;
    }

    void find_depth(TreeNode* root, vector<vector<int>>& res, vector<int>& temp, int sum)
    {
        //边界条件
        if(root == NULL)
            return;
        
        temp.push_back(root->val);
        if(root->left == NULL && root->right == NULL)
        {
            if(sum == root->val)
            {
                //根左右,压入完不要直接返回,并且temp不要清空,它会自己回溯
                res.push_back(temp);
            }
        }

        find_depth(root->left,res,temp,sum-root->val);
        find_depth(root->right,res,temp,sum-root->val);
        
        temp.pop_back();//回溯一下
    }
};

猜你喜欢

转载自blog.csdn.net/L_smartworld/article/details/107464369