其他分享
首页 > 其他分享> > LeetCode 113 Path Sum II DFS

LeetCode 113 Path Sum II DFS

作者:互联网

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]

Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22

Solution

给定一个二叉树,以及一个定值 targetSum,现要求出所有从rootleaf的路径,其总和为targetSum.
非常熟悉的\(DFS\)问题,定义 \(DFS(node,sum,paths,path)\). 其中\(node\)为当前的节点,\(sum\)表示剩余的总和,如果此时\(sum==node.val\),并且为叶子节点,那么将路径\(path\)加入\(paths\). 还需注意的一点是path.pop_back()进行回溯

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<vector<int>> paths;
        vector<int> path;
        dfs(root, targetSum, paths, path);
        return paths;
    }

    void dfs(TreeNode* root, int sum, vector<vector<int>> &paths, vector<int> &path){
        if(! root) return;
        path.push_back(root->val);
        if(!(root->left)&&!(root->right)&&(sum==root->val)){
            paths.push_back(path);
        }
        dfs(root->left, sum-(root->val), paths, path);
        dfs(root->right,sum-(root->val), paths, path);
        path.pop_back();
    }
};

标签:paths,TreeNode,val,Sum,DFS,II,path,root,sum
来源: https://www.cnblogs.com/xinyu04/p/16227153.html