C/C++教程

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();
    }
};
这篇关于LeetCode 113 Path Sum II DFS的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!