LeetCode | 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.
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)
一直只需要一个cur数组,然后递归过后使用cur.pop_back()
神器啊这个函数,它可以弹出数组最后一个元素,这样就可以像栈一样操作。
最重要的是,这一个数组可以衍生出多个数组,主要还归功于vector.pus_back()
它可以生成当前对象的拷贝,然后再放入vector中,牛…
class Solution {
public:vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> result;if(!root) return result;vector<int> cur;pathSumArr(root,sum,cur,result);return result;}void pathSumArr(TreeNode* root,int sum,vector<int> &cur,vector<vector<int>>& result){if(!root) return;cur.push_back(root->val);if(sum==root->val && !root->left && !root->right){result.push_back(cur);}pathSumArr(root->left,sum-root->val,cur,result);pathSumArr(root->right,sum-root->val,cur,result);//此句神作...cur.pop_back();}
};
LeetCode | Path Sum II相关推荐
- LeetCode Path Sum II(dfs或者bfs)
问题:给出一个树和一个数,求出从根结点到叶子结点路径和等于这个数的所有情况 思路: 1.深度优先搜索,在到达一个深度结点时,判断是否是叶子结点,并且判断和是否等于要求的数.如果满足,说明是满足条件的一 ...
- [Leetcode] Path Sum II路径和
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- functionclass[LeetCode]Path Sum II
在本篇文章中,我们主要介绍functionclass的内容,自我感觉有个不错的建议和大家分享下 每日一道理 只有启程,才会到达理想和目的地,只有拼搏,才会获得辉煌的成功,只有播种,才会有收获.只有追求 ...
- LeetCode:Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode]113.Path Sum II
[题目] Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the giv ...
- leetcode 112. Path Sum, 113. Path Sum II | 112,113. 路径总和 I, II(Java)
题目 https://leetcode.com/problems/path-sum/ https://leetcode.com/problems/path-sum-ii/ 题解 简单的遍历二叉树,不解 ...
- Leetcode: mimimum depth of tree, path sum, path sum II
思路: 简单搜索 总结: dfs 框架 1. 需要打印路径. 在 dfs 函数中假如 vector 变量, 不用 & 修饰的话就不需要 undo 2. 不需要打印路径, 可设置全局变量 ans ...
- LeetCode 113. Path Sum II
113. Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum eq ...
- 113. Path Sum II
/** 113. Path Sum II * 11.18 By Mingyang* 典型的backtracking,不过注意,这里的值可能是负数,所以不能用sum小于0来做任何判断* 1.长度标准:无 ...
最新文章
- 项目经理必读:虚拟化评估与设计14步
- zabbix加入TCP连接数及状态的监控
- cbc cryptojs 前后端_前端CryptoJS AES/DES加解密与后端PHP AES/DES加解密
- Linux中的一个命令行计算器bc简介
- Duilib教程-HelloDuilib及DuiDesigner的简单使用
- DDD 领域驱动设计:贫血模型、充血模型的深入解读
- C#/WPF程序开机自动启动
- jQuery Mobile教程:jQuery Mobile基本事件
- VLOOKUP模糊匹配的妙用
- KnockoutJS(4)-控制文本和外观绑定
- python与r语言处理excel数据_【R语言】批量读取Excel数据并合并(升级版)
- JZ1-二维数组中的查找
- 7-4 输出菱形图案 (5 分)
- 华为认证的好处是什么?考试费是多少?
- web打印实现几种方法
- fastadmin项目实战踩坑
- 三层交换机原理及实验操作
- Linux Ubuntu系统fwknop单包授权认证(SPA)流程
- 【NLP】一文理解Seq2Seq
- python去除\u3000,空格,\n等