博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Path Sum II
阅读量:5343 次
发布时间:2019-06-15

本文共 2544 字,大约阅读时间需要 8 分钟。

2014.1.8 05:38

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

Solution:

  This problem is a variation from . The difference is that you need to find out all the paths, instead of just judging the existence of these paths.

  To hold the result, extra arrays are needed. Also there needs to be one array passed as parameter, so as to record path during the recursion.

  Time and space complexities are both O(n), where n is the number of nodes in the tree.

Accepted code:

1 // 1RE, 1AC 2 /** 3  * Definition for binary tree 4  * struct TreeNode { 5  *     int val; 6  *     TreeNode *left; 7  *     TreeNode *right; 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9  * };10  */11 class Solution {12 public:13     vector
> pathSum(TreeNode *root, int sum) {14 // IMPORTANT: Please reset any member data you declared, as15 // the same Solution instance will be reused for each test case.16 int i, n;17 n = result.size();18 for(i = 0; i < n; ++i){19 result[i].clear();20 }21 result.clear();22 arr.clear();23 if(root == nullptr){24 return result;25 }26 // 1RE here, forgot to push into $arr27 arr.push_back(root->val);28 dfs(root, root->val, sum);29 arr.pop_back();30 31 return result;32 }33 private:34 vector
> result;35 vector
arr;36 37 void dfs(TreeNode *root, int sum, int target){38 if(root == nullptr){39 return;40 }41 42 if(root->left == nullptr && root->right == nullptr){43 if(sum == target){44 result.push_back(arr);45 }46 return;47 }48 49 if(root->left != nullptr){50 arr.push_back(root->left->val);51 dfs(root->left, sum + root->left->val, target);52 arr.pop_back();53 }54 if(root->right != nullptr){55 arr.push_back(root->right->val);56 dfs(root->right, sum + root->right->val, target);57 arr.pop_back();58 }59 }60 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3510009.html

你可能感兴趣的文章
java 服务重启 js 中被注释代码仍然执行
查看>>
我并不是不闻不问![C#]
查看>>
全站仪数据修正为南方cass可识别数据
查看>>
插件大全网址
查看>>
2016/4/2 json:js和jquery中轻量级数据交换格式 例: 窗口弹出 popwindow
查看>>
ABAP EXCEL数据上传时因为栏位字符串过长而被截断的问题解决方法
查看>>
CF1076E Vasya and a Tree
查看>>
Linux 的基本操作(文件与目录管理)
查看>>
LeetCode 9. Palindrome Number
查看>>
python——排序
查看>>
同时使用Binding&StringFormat 显示Text【项目】
查看>>
过拟合与欠拟合 之原因和解决方法
查看>>
线段树+差分【p1438】无聊的数列
查看>>
如何修炼成某一领域的高手?
查看>>
关于deepin上谷歌浏览器会出现延时的问题
查看>>
Mobility Express部署外部镜像服务器
查看>>
关于Mobility Express转LAP注意事项
查看>>
web前端经典小题
查看>>
AutoCAD如何倒角 倒圆角 倒直角
查看>>
Office PPT中如何插入flash
查看>>