《Cracking the Coding Interview》——第4章:树和图——题目9
2014-03-19 05:07
题目:给定一棵二叉树T和一个值value,在T中找出所有加起来和等于value的路径。路径的起点和终点都可以是树的任意节点。
解法:我偷了个懒,直接把这棵树看成一个无向图,用DFS来进行暴力搜索解决问题。因为没有什么数据顺序或是范围的限制,所以搜索剪枝好像也不太容易。
代码:
// 4.9 Find all paths in a binary tree, the path doesn't have to start or end at the root or a leaf node.
#include <cstdio>
#include <unordered_map>
#include <unordered_set>
using namespace std; struct TreeNode {
int val;
TreeNode *left;
TreeNode *right; TreeNode(int _val = ):val(_val), left(nullptr), right(nullptr) {};
}; void constructTree(TreeNode *&root)
{
int val; scanf("%d", &val);
if (val == ) {
root = nullptr;
} else {
root = new TreeNode(val);
constructTree(root->left);
constructTree(root->right);
}
} void constructGraph(TreeNode *root, unordered_map<TreeNode *, unordered_set<TreeNode *> > &graph)
{
if (root->left != nullptr) {
graph[root].insert(root->left);
graph[root->left].insert(root);
constructGraph(root->left, graph);
} if (root->right != nullptr) {
graph[root].insert(root->right);
graph[root->right].insert(root);
constructGraph(root->right, graph);
}
} void DFS(TreeNode *node, vector<TreeNode *> &path, int sum, const int target,
unordered_set<TreeNode *> &checked,
unordered_map<TreeNode *, unordered_set<TreeNode *> > &graph, vector<vector<TreeNode *> > &result)
{
path.push_back(node);
checked.insert(node); if (sum == target) {
result.push_back(path);
}
unordered_set<TreeNode *>::iterator it;
for (it = graph[node].begin(); it != graph[node].end(); ++it) {
if (checked.find(*it) == checked.end()) {
DFS(*it, path, sum + (*it)->val, target, checked, graph, result);
}
} checked.erase(node);
path.pop_back();
} void doDFS(TreeNode *root, vector<TreeNode *> &path, const int target,
unordered_set<TreeNode *> &checked,
unordered_map<TreeNode *, unordered_set<TreeNode *> > &graph, vector<vector<TreeNode *> > &result)
{
path.clear();
checked.clear();
DFS(root, path, root->val, target, checked, graph, result);
if (root->left != nullptr) {
doDFS(root->left, path, target, checked, graph, result);
}
if (root->right != nullptr) {
doDFS(root->right, path, target, checked, graph, result);
}
} void clearTree(TreeNode *&root)
{
if (root == nullptr) {
return;
} if (root->left != nullptr) {
clearTree(root->left);
}
if (root->right != nullptr) {
clearTree(root->right);
}
delete root;
root = nullptr;
} int main()
{
int i, j;
int target;
TreeNode *root;
unordered_map<TreeNode *, unordered_set<TreeNode *> > graph;
unordered_map<TreeNode *, unordered_set<TreeNode *> >::iterator it;
unordered_set<TreeNode *> checked;
vector<TreeNode *> path;
vector<vector<TreeNode *> > result; while (true) {
constructTree(root);
if (root == nullptr) {
break;
}
constructGraph(root, graph);
while (scanf("%d", &target) == && target) {
doDFS(root, path, target, checked, graph, result);
if (result.empty()) {
printf("No path is found.\n");
} else {
for (i = ; i < (int)result.size(); ++i) {
printf("%d", result[i][]->val);
for (j = ; j < (int)result[i].size(); ++j) {
printf("->%d", result[i][j]->val);
}
result[i].clear();
printf("\n");
}
result.clear();
}
path.clear();
checked.clear();
}
for (it = graph.begin(); it != graph.end(); ++it) {
(it->second).clear();
}
graph.clear();
clearTree(root);
} return ;
}
《Cracking the Coding Interview》——第4章:树和图——题目9的更多相关文章
- Cracking the coding interview 第一章问题及解答
Cracking the coding interview 第一章问题及解答 不管是不是要挪地方,面试题具有很好的联系代码总用,参加新工作的半年里,做的大多是探索性的工作,反而代码写得少了,不高兴,最 ...
- 《Cracking the Coding Interview》读书笔记
<Cracking the Coding Interview>是适合硅谷技术面试的一本面试指南,因为题目分类清晰,风格比较靠谱,所以广受推崇. 以下是我的读书笔记,基本都是每章的课后习题解 ...
- Cracking the coding interview
写在开头 最近忙于论文的开题等工作,还有阿里的实习笔试,被虐的还行,说还行是因为自己的水平或者说是自己准备的还没有达到他们所需要人才的水平,所以就想找一本面试的书<Cracking the co ...
- Cracking the Coding Interview(Trees and Graphs)
Cracking the Coding Interview(Trees and Graphs) 树和图的训练平时相对很少,还是要加强训练一些树和图的基础算法.自己对树节点的设计应该不是很合理,多多少少 ...
- Cracking the coding interview目录及资料收集
前言 <Cracking the coding interview>是一本被许多人极力推荐的程序员面试书籍, 详情可见:http://www.careercup.com/book. 第六版 ...
- Cracking the Coding Interview(Stacks and Queues)
Cracking the Coding Interview(Stacks and Queues) 1.Describe how you could use a single array to impl ...
- 二刷Cracking the Coding Interview(CC150第五版)
第18章---高度难题 1,-------另类加法.实现加法. 另类加法 参与人数:327时间限制:3秒空间限制:32768K 算法知识视频讲解 题目描述 请编写一个函数,将两个数字相加.不得使用+或 ...
- Cracking the Coding Interview 150题(二)
3.栈与队列 3.1 描述如何只用一个数组来实现三个栈. 3.2 请设计一个栈,除pop与push方法,还支持min方法,可返回栈元素中的最小值.pop.push和min三个方法的时间复杂度必须为O( ...
- 《Cracking the Coding Interview》——第4章:树和图——题目8
2014-03-19 05:04 题目:给定两棵二叉树T1和T2,判断T2是否是T1的子树.子树的定义是,以T1的某个节点(可以是T1的根)作为根节点,得到的这棵树和T2一模一样. 解法:首先可以根据 ...
随机推荐
- simotion byte/word ASCII码转换为字符、字符串
建立string类型,和byte类型(ASCII)的数据 将byte类型(ASCII)赋值给string中的一个字符 参考程序 VAR_GLOBAL myword :WORD; mystring :S ...
- org.apache.xmlbeans.XmlException: error: does not close tag
使用myeclipse的jax自动生成webservice , 或者serviceImpl通过@webservice来实现webservice时, 使用soap UI (我测试使用的版本 5.2.1) ...
- IOS 拼接按钮文字
NSMutableString *tempAnswerTitle=[[NSMutableString alloc]init]; for(UIButton *answerBtn in self.answ ...
- ABI and ISA
ABI定义了如何使用ISA. ISA定义了机器码的使用规则. http://www.delorie.com/gnu/docs/gmp/gmp_6.html ABI and ISA ABI (Appli ...
- 【转】css行高line-height的一些深入理解及应用
一.前言 前两天在腾讯ISD团队博客上看到一篇翻译的文章“深入理解css 行高”,是个不错的文章,学到了不少东西,建议您看看. 这里,我也要讲讲我对line-height的一些理解,所讲解的东西绝大多 ...
- java获取文件后缀名(正则表达式)+文件名
String fileName="asadas.jsp"; String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.png|.PNG)$" ...
- python的**和*
1.**两个乘号就是乘方,比如2**4,结果就是2的4次方,结果是16一个乘号*,如果操作数是两个数字,就是这两个数字相乘,如2*4,结果为8*如果是字符串.列表.元组与一个整数N相乘,返回一个其所有 ...
- 深入理解 SVG 系列(一) —— SVG 基础
来源:https://segmentfault.com/a/1190000015652209 本系列文章分为三个部分: 第一部分是 SVG 基础. 主要讲 SVG 的一些基础知识,包括 SVG 基本元 ...
- 经典sql语句汇总
1,某条数据放首位,其他倒序并分页 select * from Student order by( case when id='2' then 1 ELSE 4 END),id desc l ...
- 使用myeclipse创建servlet后输入地址无法访问
问题: 使用myeclipse创建servlet后输入地址无法访问 1.首先,路径的访问地址是在web.xml里设置的,一般会自动生成(但是可能会和你自己输入的有出入) 你必须按照<url-pa ...