LEETCODE,LeetCode OJ - Path Sum II

 2023-10-07 阅读 29 评论 0

摘要:題目: 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] ] 解題思路

題目:

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

解題思路:

簡單的DFS。

代碼:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 
11 class Solution {
12 public:
13     int vec_sum(vector<int> &cur_ans) {
14         int sum = 0;
15         for (int i = 0; i < cur_ans.size(); i++) {
16             sum += cur_ans[i];
17         }
18         return sum;
19     }
20     void search_dfs(TreeNode *root, vector<int> &cur_ans, int sum, vector<vector<int>> &ans) {
21         if (root->left == NULL && root->right == NULL) {
22             cur_ans.push_back(root->val);
23             if (vec_sum(cur_ans) == sum) ans.push_back(cur_ans);
24             cur_ans.pop_back();
25         }
26         else {
27             cur_ans.push_back(root->val);
28             if (root->left != NULL) search_dfs(root->left, cur_ans, sum, ans);
29             if (root->right != NULL) search_dfs(root->right, cur_ans, sum, ans);
30             cur_ans.pop_back();
31         }
32         return;
33     }
34     vector<vector<int> > pathSum(TreeNode *root, int sum) {
35         vector<vector<int>> ans;
36         if (root == NULL) return ans;
37 
38         vector<int> cur_ans;
39         
40         search_dfs(root, cur_ans, sum, ans);
41         return ans;
42     }
43 };

?

LEETCODE?轉載于:https://www.cnblogs.com/dongguangqing/p/3728037.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/126224.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息