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的更多相关文章

  1. Cracking the coding interview 第一章问题及解答

    Cracking the coding interview 第一章问题及解答 不管是不是要挪地方,面试题具有很好的联系代码总用,参加新工作的半年里,做的大多是探索性的工作,反而代码写得少了,不高兴,最 ...

  2. 《Cracking the Coding Interview》读书笔记

    <Cracking the Coding Interview>是适合硅谷技术面试的一本面试指南,因为题目分类清晰,风格比较靠谱,所以广受推崇. 以下是我的读书笔记,基本都是每章的课后习题解 ...

  3. Cracking the coding interview

    写在开头 最近忙于论文的开题等工作,还有阿里的实习笔试,被虐的还行,说还行是因为自己的水平或者说是自己准备的还没有达到他们所需要人才的水平,所以就想找一本面试的书<Cracking the co ...

  4. Cracking the Coding Interview(Trees and Graphs)

    Cracking the Coding Interview(Trees and Graphs) 树和图的训练平时相对很少,还是要加强训练一些树和图的基础算法.自己对树节点的设计应该不是很合理,多多少少 ...

  5. Cracking the coding interview目录及资料收集

    前言 <Cracking the coding interview>是一本被许多人极力推荐的程序员面试书籍, 详情可见:http://www.careercup.com/book. 第六版 ...

  6. 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 ...

  7. 二刷Cracking the Coding Interview(CC150第五版)

    第18章---高度难题 1,-------另类加法.实现加法. 另类加法 参与人数:327时间限制:3秒空间限制:32768K 算法知识视频讲解 题目描述 请编写一个函数,将两个数字相加.不得使用+或 ...

  8. Cracking the Coding Interview 150题(二)

    3.栈与队列 3.1 描述如何只用一个数组来实现三个栈. 3.2 请设计一个栈,除pop与push方法,还支持min方法,可返回栈元素中的最小值.pop.push和min三个方法的时间复杂度必须为O( ...

  9. 《Cracking the Coding Interview》——第4章:树和图——题目8

    2014-03-19 05:04 题目:给定两棵二叉树T1和T2,判断T2是否是T1的子树.子树的定义是,以T1的某个节点(可以是T1的根)作为根节点,得到的这棵树和T2一模一样. 解法:首先可以根据 ...

随机推荐

  1. 【js基础修炼之路】— 我理解的原型链

    提起原型链,大家并不陌生,但是对于新人来说一提到原型方面的东西就会比较懵.在我自一次面试的时候,面试官也给我提了这样的问题,当时就按照我的理解说了一些,但是很肤浅,在此我希望给刚入门的前端小伙伴聊一下 ...

  2. Jenkins使用分组过滤分类

    背景:Jenkins项目过多,通过选项卡的方式过滤需要的项目 1.点击选择卡上的加号 2.填写要分组的名字 3.可选择某个job进行分类,或者使用正则表达式的方式进行分类,楼主是根据正则进行匹配, 4 ...

  3. 课程设计__继承与派生,重载<<

    ///继承与派生 #include <iostream> using namespace std; class Point { public: Point (,):x(a),y(b) {} ...

  4. material(一)

    项目目录如下 逻辑代码 import React from 'react'; import PropTypes from 'prop-types'; import Button from '@mate ...

  5. 【杂题总汇】HDU多校赛第十场 Videos

    [HDU2018多校赛第十场]Videos 最后一场比赛也结束了…… +HDU传送门+ ◇ 题目 <简要翻译> 有n个人以及m部电影,每个人都有一个快乐值.每场电影都有它的开始.结束时间和 ...

  6. Spring Boot Common application properties(转载)

    转自官方文档:http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.h ...

  7. Hibernate进阶学习3

    Hibernate进阶学习3 测试hibernate的多表关联操作(一对多,多对一,多对多) 表之间的关系主要在类与元数据配置文件中体现 package com.hibernate.domain; i ...

  8. MySQL的where条件优化

    where 条件优化  适合select delete update   1.避免无用的括号 ((a AND b) AND c OR (((a AND b) AND (c AND d)))) -> ...

  9. 聊聊我这两年都在忙什么,IT技术男如何转型!

    从09年开始,从事软件测试工作:至今六年有余: 从当初的简单的功能测试,到后来的整体系统测试,性能测试,至公司测试负责人: 我常常在想,IT技术男,有哪些转型机会,是不是得一辈子从事测试这个职业(注: ...

  10. 基于Select模型通信程序的编写,编译和执行

    任务目标 编写Win32程序模拟实现基于Select模型的两台计算机之间的通信,要求编程实现服务器端与客户端之间双向数据传递.客户端向服务器端发送"计算从1到100的奇数和",服务 ...