【IT笔试面试题整理】判断一个树是否是另一个的子树
来源:互联网 发布:python视频教程在线 编辑:程序博客网 时间:2024/05/22 02:10
【试题描述】定义一个函数,输入判断一个树是否是另一个对的子树
You have two very large binary trees: T1, with millions of nodes, and T2, with hun-dreds of nodes Create an algorithm to decide if T2 is a subtree of T1
Note that the problem here specifies that T1 has millions of nodes—this means that we should be careful of how much space we use Let’s say, for example, T1 has 10 million nodes—this means that the data alone is about 40 mb We could create a string representing the inorder and preorder traversals If T2’s preorder traversal is a substring of T1’s preorder traversal, and T2’s inorder traversal is a substring of T1’s inorder traversal, then T2 is a sub-string of T1 We can check this using a suffix tree However, we may hit memory limitations because suffix trees are extremely memory intensive If this become an issue, we can use an alternative approach Alternative Approach: The treeMatch procedure visits each node in the small tree at most once and is called no more than once per node of the large tree Worst case runtime is at most O(n * m), where n and m are the sizes of trees T1 and T2, respectively If k is the number of occurrences of T2’s root in T1, the worst case runtime can be characterized as O(n + k * m)
【参考代码】
1 boolean containsTree(Node t1, Node t2) 2 { 3 if (t2 == null) 4 return true; 5 else 6 return subTree(t1, t2); 7 } 8 9 boolean subTree(Node r1, Node r2)10 {11 if (r1 == null)12 return false;13 if (r1.value == r2.value)14 {15 if (matchTree(r1, r2))16 return true;17 }18 return (subTree(r1.left,r2) || subTree(r1.right,r2));19 }20 21 boolean matchTree(Node r1, Node r2)22 {23 if (r2 == null && r1 == null)24 return true;25 if (r1 == null || r2 == null)26 return false;27 if (r1.value != r2.value)28 return false;29 return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right));30 }
- 【IT笔试面试题整理】判断一个树是否是另一个的子树
- 【IT笔试面试题整理】判断一个二叉树是否是平衡的?
- 判断一个树是否是另一个树的子树
- 判断一个二叉树是否是另一个的子树
- 利用KMP算法判断一个树是否是另一个树的子树
- 判断一个二叉树是否是另一个二叉树的子树
- 判断一个二叉树是否是另一个二叉树的子树
- 判断一个树是否为另一个树的子树
- 判断一个树是否为另一个树的子树
- 百度笔试题:判断一个二叉树是否是另一颗二叉树的子树
- 【IT笔试面试题整理】判定一棵二叉树是否是二叉搜索树-转
- 判断一个树是否是另外一个树的子树
- 判断一颗树是否是另外一个树的子树
- 【python】判断一棵树是否是另外一个树的子树
- 【IT笔试面试题整理】判断链表是否存在环路,并找出回路起点
- 【面试题】剑指offer18--判断一个二叉树是否为另一个二叉树的子结构
- 剑指offer面试题18判断一个二叉树是否包含另一个的递归算法
- 如何判断一个二叉树是否为另一个二叉树的子树
- 【IT笔试面试题整理】判断链表是否存在环路,并找出回路起点
- 【IT笔试面试题整理】判断一个二叉树是否是平衡的?
- 关于笔记本安装Deepin 或者ubuntu操作系统,无法进入界面。
- 【IT笔试面试题整理】删除无序链表中重复的节点
- 如何配置MySQL数据库超时设置
- 【IT笔试面试题整理】判断一个树是否是另一个的子树
- 【IT笔试面试题整理】有序数组生成最小高度二叉树
- 【IT笔试面试题整理】给定二叉树,给每层生成一个链表
- XSS漏洞手工检测
- 【IT笔试面试题整理】位操作
- maven------junit作用
- 【IT笔试面试题整理】链表
- 【IT笔试面试题整理】堆栈和队列
- 【IT笔试面试题整理】给定二叉树先序中序,建立二叉树的递归算法