113. Path Sum II**

113. Path Sum II**

https://leetcode.com/problems/path-sum-ii/

题目描述

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

Note: A leaf is a node with no children.

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

C++ 实现 1

思路是使用 dfs 来遍历从根节点到叶子节点的所有路径, 如果这条路径上所有节点之和等于 sum, 那么就保存下来.

下面再额外说一下 dfs 中关于 cur.pop_back() 这一步, 之所以只用一个 pop_back(), 是因为如果到达了叶子节点, 此时 leaf_node->left 以及 leaf_node->right 都为空, 那么两个 dfs(root->left)dfs(root->right) 都直接返回, 但是此时 cur.push_back(root->val) 还保留着 root->val, 为了达到回溯的目的, 需要对这个值进行 pop_back. 在后面的 补充 中提供了遍历整棵二叉树所有路径的代码.

/**
 * 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 {
private:
    void dfs(TreeNode* root, int sum, vector<int> &cur, vector<vector<int>> &res) {
        if (!root) return;
        cur.push_back(root->val);
        if (!root->left && !root->right && root->val == sum)
            res.push_back(cur);
        dfs(root->left, sum - root->val, cur, res);
        dfs(root->right, sum - root->val, cur, res);
        cur.pop_back();
    }
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        if (!root || (!root->left && !root->right && root->val != sum)) return {};
        vector<vector<int>> res;
        vector<int> cur;
        dfs(root, sum, cur, res);
        return res;
    }
};

补充

遍历整棵二叉树的代码.

只需要 pop_back 一次.

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

或者更为冗余一点的写法:

void dfs(TreeNode* root, vector<int> &cur, vector<vector<int>> &res) {
        if (!root) return;
        cur.push_back(root->val);
        if (!root->left && !root->right)
            res.push_back(cur);
        dfs(root->left, cur, res);
        if (root->left) cur.pop_back();
        dfs(root->right, cur, res);
        if (root->right) cur.pop_back();
}
发布了352 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104531260