【LeetCode-回溯】二叉树中和为某一值的路径

题目描述

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:

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

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

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

说明: 节点总数 <= 10000
题目链接: https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/

思路

使用回溯来做,使用回溯来做的一个特点就是在递归的过程中要做选择,为了做不同的选择,我们需要把之前的选择撤销掉。

代码如下:

/**
 * 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) {
        if(root==nullptr) return {};

        vector<vector<int>> ans;
        vector<int> path;
        path.push_back(root->val);  // 先把 root 放进路径中
        dfs(root, sum, root->val, path, ans);
        return ans;
    }

    void dfs(TreeNode*& root, int& sum, int curSum, vector<int> path, vector<vector<int>>& ans){
        if(curSum==sum && root->left==nullptr && root->right==nullptr){  // 注意,不只要相等,还要是叶子节点
            ans.push_back(path);
            return;
        }

        if(root->left!=nullptr){
            curSum += root->left->val;
            path.push_back(root->left->val);
            dfs(root->left, sum, curSum, path, ans);
            path.pop_back();
            curSum -= root->left->val;
        }
        if(root->right!=nullptr){
            curSum += root->right->val;
            path.push_back(root->right->val);
            dfs(root->right, sum, curSum, path, ans);
            path.pop_back();
            curSum -= root->right->val;
        }
    }
};

代码简化:

/**
 * 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) {
        if(root==nullptr) return {};

        vector<int> path;
        vector<vector<int>> ans;
        dfs(root, sum, path, ans);
        return ans;
    }

    void dfs(TreeNode* root, int sum, vector<int> path, vector<vector<int>>& ans){
        if(root==nullptr) return;

        path.push_back(root->val);
        if(sum-root->val==0 && root->left==nullptr && root->right==nullptr){
            ans.push_back(path);
            return;
        }
        dfs(root->left, sum-root->val, path, ans);
        dfs(root->right, sum-root->val, path, ans);
        path.pop_back();  // 别忘了这一步
    }
};

猜你喜欢

转载自www.cnblogs.com/flix/p/13372714.html