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

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

一.题目

Path Sum II

  
Total Accepted: 46778 
Total Submissions: 175830

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

Show Tags
Have you met this question in a real interview?  
Yes
 
No

二.解题技巧

    这道题和类似,仅仅只是这道题须要找到全部和等于给定值的路径,因此不能在中间部分进行剪枝。必须遍历全然部的路径。

这里面有一个技巧,在进入每个结点的时候。先将该结点的值push到vector中。在退出时间该结点的值pop出来,这样就能够避免有时会忘记pop结点的值的情况。

    这样的做法的时间复杂度为O(n),空间复杂度为O(logn)。

三.实现代码

#include 
#include
using std::vector;/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution{private: void pathSum(TreeNode* root, int sum, vector
> &Result, vector
&TmpResult) { if (!root) { return; } if (!root->left && !root->right && root->val == sum) { TmpResult.push_back(sum); Result.push_back(TmpResult); // pop the leaf node TmpResult.pop_back(); return; } int SumChild = sum - root->val; TmpResult.push_back(root->val); pathSum(root->left, SumChild, Result, TmpResult); pathSum(root->right, SumChild, Result, TmpResult); // pop the current node TmpResult.pop_back(); }public: vector
> pathSum(TreeNode* root, int sum) { vector
> Result; vector
TmpResult; pathSum(root, sum, Result, TmpResult); return Result; }};

四.体会

    这道题和类似,解法也是同样的吗。仅仅是不能进行剪枝而已。
版权全部,欢迎转载。转载请注明出处,谢谢微笑
你可能感兴趣的文章
Java的内存模型
查看>>
安装memcached
查看>>
Windows计算机重置TCP / IP
查看>>
SinoBBD亮相全球云计算大会 彰显一体化云力量
查看>>
AndroidStudio调用so文件
查看>>
Hadoop常用下载地址
查看>>
Oracle 分区表的新增、修改、删除、合并。普通表转分区表方法
查看>>
根据MAC地址查询网卡厂商
查看>>
菜鸟末端配送机器人年内投入商用!下一步要研发卡车
查看>>
[前端]JS时钟实例
查看>>
阿里云CentOS搭建Linux系统
查看>>
39、BGP配置实验之基础配置
查看>>
oj1330Nearest Common Ancestors 1470 Closest Common Ancestors(LCA算法)
查看>>
数据库之触发器
查看>>
14种网站最差的用户体验
查看>>
菜鸟学Linux 第017篇笔记 sed命令的使用
查看>>
python 字符串重要方法
查看>>
思科设置口令和控制台口令
查看>>
导出excel文件
查看>>
SED单行脚本快速参考
查看>>