1. 程式人生 > >[Leetcode Week14]Path Sum II

[Leetcode Week14]Path Sum II

這樣的 節點 原創 就是 題目 als 葉子節點 pat span

Path Sum II 題解

原創文章,拒絕轉載

題目來源:https://leetcode.com/problems/path-sum-ii/description/


Description

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

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]
]

Solution

class Solution {
    void dfs(vector<vector<int>>& res, vector<int>& path, TreeNode* root, int sum) {
        if (root -> left == NULL && root -> right == NULL) {
            if (sum == root -> val) {
                path.push_back(root -> val);
                res.push_back(path);
                path.pop_back();
            }
            return
; } if (root -> left != NULL) { path.push_back(root -> val); dfs(res, path, root -> left, sum - (root -> val)); path.pop_back(); } if (root -> right != NULL) { path.push_back(root -> val); dfs(res, path, root -> right, sum - (root -> val)); path.pop_back(); } } public
: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; if (root == NULL) return res; vector<int> path; dfs(res, path, root, sum); return res; } };

解題描述

這道題目題意是,在一棵二叉樹中,尋找一個從根節點到葉子節點的路徑,使得路徑上的數字之和為給定的數字sum,要求找出所有這樣的路徑。當然最容易想到的就是使用DFS來解決。

[Leetcode Week14]Path Sum II