算法课第3周第1题——113. Path Sum II

来源:互联网 发布:路由器访客网络是什么 编辑:程序博客网 时间:2024/05/20 19:28

题目描述:

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

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


程序代码:

/** * 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) { vector<int> vec; vector <vector<int>> res; recur(root, sum, vec, res); return res; } // 递归用函数 void recur(TreeNode* root, int sum, vector<int> vec, vector <vector<int>> &res) { // 当root为空 if (root == NULL) { return; } // 当root不为空且左右子节点为空时(root为叶子节点) else if (root->left == NULL && root->right == NULL) { // 刚好等于sum if (sum == root->val) { vec.push_back(root->val); res.push_back(vec); // vec.pop_back();  } } // 当root不为空且不为叶子结点 else { int nextSum = sum - root->val; vec.push_back(root->val); recur(root->left, nextSum, vec, res); recur(root->right, nextSum, vec, res); } } };


简要题解:

本题有是一道关于二叉树和递归的题目,也运用了一些DFS的思想。

本题需要返回一个二叉树中从根到叶子结点上的数之和刚好等于sum值的所有路径。首先,先运用类似DFS的解法,建立一个递归函数recur,在这个函数中,判断root是否为空,若为空则直接返回。若root不为空且左右子结点为空时(即root为叶子结点时),如果sum的值刚好等于root中的数值,则将root的数值加入到向量vec的尾部,并将vec加入到向量res的尾部(res是本题最后返回的结果向量);而当root不为空也不为叶子结点时,将原sum的值减去root中的数值作为传递到下一个函数的nextSum值,并将root中的数值加入vec的尾部,对root的左、右子节点分别调用函数recur做递归。这样递归之后,向量res尾部就会不断加入所有符合题意的向量。最后,只需要在pathSum函数中对二叉树的根节点调用recur函数,并返回向量res即可。要注意的是,recur函数中参数vector<vector<int>> &res需要是引用,来保证每次递归都会实际修改res的值。

二叉树是图最为简单的一种形式,通过本题的练习,我为后面熟悉图的各种算法做好了铺垫。同时,本题也用到了类似DFS的思想,也算是对本周课程内容的一个复习。

0 0