4.8 You have two very large binary trees: Tl, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of Tl. A tree T2 is a subtree of Tl if there exists a node n in Tl such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

这道题给我们两棵树,T1和T2,其中T1有百万个节点,T2有上百个节点,让我们写算法来判断T2是不是T1的子树。首先可以用的方法是,我们对两棵树分别进行前序和中序遍历,然后把结果分别存入字符串中,如果T2的前序和中序遍历的字符串分别是T1的前序和中序遍历的字符串的子串,那么我们可以判定T2是T1的子树,参见代码如下:

解法一:

class Solution {
public:
bool containTree(TreeNode *root1, TreeNode *root2) {
string pre1, pre2, in1, in2;
preorder(root1, pre1);
preorder(root2, pre2);
inorder(root1, in1);
inorder(root2, in2);
if (pre1.find(pre2) == pre1.size() - pre2.size() && in1.find(in2) == in1.size() - in2.size()) return true;
else return false;
}
void preorder(TreeNode *root, string &res) {
if (!root) return;
res.append(to_string(root->val));
preorder(root->left, res);
preorder(root->right, res);
}
void inorder(TreeNode *root, string &res) {
if (!root) return;
inorder(root->left, res);
res.append(to_string(root->val));
inorder(root->right, res);
}
};

但是上面这种解法存在例外情况无法正确分辨,比如下面的两棵树:

3                       3

/           and            \

3                                 3

它们的中序和前序遍历都相同,所以上述算法会返回true,但我们知道它们是两个不同的树,谁也不包含谁,谁也不是谁的子树。Cracking the Coding Interview 5th Edition这书上第235页上说我们可以标记处空节点,但这种方法麻烦,又占空间,所以这里我不去写它。下面来看书上给出的另一种解法,这种解法的思路是,我们首先判断T2是否为空,为空则直接返回True,因为空树是任何树的子树,然后我们看T1是否为空,T1为空直接返回false,因为空树不可能有非空子树,然后我们看两个根节点的值是否相同,如果相同,则调用matchTree方法,来比较整个T2树,如果完全匹配则返回true,否则继续往下递归,参见代码如下:

解法二:

class Solution {
public:
bool containTree(TreeNode *root1, TreeNode *root2) {
if (!root2) return true;
if (!root1) return false;
if (root1->val == root2->val) {
if (matchTree(root1, root2)) return true;
}
return containTree(root1->left, root2) || containTree(root1->right, root2);
}
bool matchTree(TreeNode *root1, TreeNode *root2) {
if (!root1 && !root2) return true;
if (!root1 || !root2) return false;
if (root1->val != root2->val) return false;
else (matchTree(root1->left, root2->left) && matchTree(root1->right, root2->right));
}
};

[CareerCup] 4.8 Contain Tree 包含树的更多相关文章

  1. [转] Splay Tree(伸展树)

    好久没写过了,比赛的时候就调了一个小时,差点悲剧,重新复习一下,觉得这个写的很不错.转自:here Splay Tree(伸展树) 二叉查找树(Binary Search Tree)能够支持多种动态集 ...

  2. 【数据结构】B-Tree, B+Tree, B*树介绍 转

    [数据结构]B-Tree, B+Tree, B*树介绍 [摘要] 最近在看Mysql的存储引擎中索引的优化,神马是索引,支持啥索引.全是浮云,目前Mysql的MyISAM和InnoDB都支持B-Tre ...

  3. B-Tree, B+Tree, B*树介绍

    [数据结构]B-Tree, B+Tree, B*树介绍 转   [数据结构]B-Tree, B+Tree, B*树介绍 [摘要] 最近在看Mysql的存储引擎中索引的优化,神马是索引,支持啥索引.全是 ...

  4. 一步一步分析Gin框架路由源码及radix tree基数树

    Gin 简介 Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much ...

  5. Mysql存储引擎之TokuDB以及它的数据结构Fractal tree(分形树)

    在目前的Mysql数据库中,使用最广泛的是innodb存储引擎.innodb确实是个很不错的存储引擎,就连高性能Mysql里都说了,如果不是有什么很特别的要求,innodb就是最好的选择.当然,这偏文 ...

  6. 页面设计--Tree目录树

    Tree目录树控件属性: 根据数据集合来配置相应的信息 加载模式有自动加载.自定加载 web中显示效果图:

  7. CJOJ 1976 二叉苹果树 / URAL 1018 Binary Apple Tree(树型动态规划)

    CJOJ 1976 二叉苹果树 / URAL 1018 Binary Apple Tree(树型动态规划) Description 有一棵苹果树,如果树枝有分叉,一定是分2叉(就是说没有只有1个儿子的 ...

  8. [Flex] 组件Tree系列 —— 运用LabelFunction hasChildren getChildren设置Tree包含节点个数

    mxml: <?xml version="1.0" encoding="utf-8"?> <!--功能描述:运用LabelFunction h ...

  9. poj 1741 Tree(树的点分治)

    poj 1741 Tree(树的点分治) 给出一个n个结点的树和一个整数k,问有多少个距离不超过k的点对. 首先对于一个树中的点对,要么经过根结点,要么不经过.所以我们可以把经过根节点的符合点对统计出 ...

随机推荐

  1. mybatis java.lang.UnsupportedOperationException

    mybatis抛出下面的异常: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exc ...

  2. DataTable转List<Model>通用类

    /// <summary> /// DataTable转List<Model>通用类[实体转换辅助类] /// </summary> public class Mo ...

  3. AngularJS的一点学习笔记

    ng-options="item.action for item in todos" ng-options表达式的基本形式, 形如 "<标签> for < ...

  4. myeclipe eclipse 常遇问题:Some projects cannot be imported 、java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver、The file connot be validate

    1.Some projects cannot be imported because they already exist in the workspace 2.Some projects were ...

  5. linux进程间通信-概述

    一 进程间通信有如下的目的: 1.数据传输,一个进程需要将它的数据发送给另一个进程,发送的数据量在一个字节到几M之间:2.共享数据,多个进程想要操作共享数据,一个进程对数据的修改,其他进程应该立刻看到 ...

  6. IPC之PIPE

    管道是一种只允许用在有亲属关系的进程间通信的方式,由函数pipe创建一个管道,read,write进行读写操作. #include <unistd.h> ]); 参数pipefd[2]数组 ...

  7. [嵌入式学习资料]ARM开发学习详解iTOP-4412开发板使用手册

    拿到的最新4412开发板学习使用手册,完全免费,分享一下 下载地址:http://pan.baidu.com/s/1ntrJA8h

  8. 边工作边刷题:70天一遍leetcode: day 85-4

    Walls and Gates 要点: 同样是bfs,这题可以用渲染的方法(即全部gate进初始q),注意区别Shortest Distance from All Buildings.那道题要找到某个 ...

  9. CBT 简介

    http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalI ...

  10. codeforces 712B B. Memory and Trident(水题)

    题目链接: B. Memory and Trident time limit per test 2 seconds memory limit per test 256 megabytes input ...