《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一模一样. 解法:首先可以根据 ...
随机推荐
- 笨办法学Python(十三)
习题 13: 参数.解包.变量 在这节练习中,我们将讲到另外一种将变量传递给脚本的方法(所谓脚本,就是你写的 .py 程序).你已经知道,如果要运行 ex13.py,只要在命令行运行 python e ...
- TP5.1:数据库的增删改查操作(基于数据库操作)
1.在app/index/controller文件夹下创建一个文件,名为:Operation 注意:起名一定要避开关键字,例如:mysql,curd等等,如果使用关键字起名,会造成报错! 在Opera ...
- *1 Two Sum two pointers(hashmap one scan)
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- python web应用--WSGI接口(二)
WSGI接口定义非常简单,它只要求Web开发者实现一个函数,就可以响应HTTP请求.我们来看一个最简单的Web版本的“Hello, web!”: 1 # server.py 2 # 从wsgiref模 ...
- 2018年第九届蓝桥杯【C++省赛B组】第四题 测试次数
x星球的居民脾气不太好,但好在他们生气的时候唯一的异常举动是:摔手机.各大厂商也就纷纷推出各种耐摔型手机.x星球的质监局规定了手机必须经过耐摔测试,并且评定出一个耐摔指数来,之后才允许上市流通.x星球 ...
- 简单介绍Spring是什么?
对于面试者回答什么是Spring,这个问题占6分分值,分值点分布:1.Spring的核心是一个轻量级(Lightweight)的容器(Container).2.Spring是实现IoC(Inversi ...
- DESCryptoServiceProvider 类加密解密
DESCryptoServiceProvider 点击查看介绍 加密解密辅助类:点击查看 私钥加密 定义:定义一个包装对象来访问加密服务提供程序 (CSP) 版本的数据加密标准 (DES) 算法. ...
- Python,针对指定文件类型,过滤空行和注释,统计行数
参考网络上代码编辑而成,无技术含量,可自行定制: 目前亲测有效,若有待完善之处,还望指出! 强调:将此统计py脚本放置项目的根目录下执行即可. 1.遍历文件,递归遍历文件夹中的所有 def getFi ...
- Java之 jstl 自定义标签的方法
1.写一个Java类 我的路径是写再tag包中的一个 HelloTag类 package tag; import java.io.IOException; import javax.servlet.j ...
- spring-AspectJ
动态代理 ProxyFactoryBean织入切面数量太多不利于围护 BeanNameAutoProxyCreater-------------根据Bean名称创建代理 DefaultAdvisorA ...