剑指offer-第三章高质量代码(树的子结构)
题目:输入两个二叉树A和B,判断B是不是A的子结构。
思路:遍历A树找到B树的根节点,然后再判断左右子树是否相同。不相同再往下找。重复改过程。
子结构的描述如下图所示:
C++代码:
#include<iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* ConstructCore(int* startPreorder,int* endPreorder,int* startInorder,int* endInorder)
{
int rootValue=startPreorder[];
BinaryTreeNode* root=new BinaryTreeNode();
root->m_nValue=rootValue;
root->m_pLeft=root->m_pRight=NULL;
if(startPreorder==endPreorder)
{
if(startInorder==endInorder&&*startPreorder==*startInorder)
{
return root;
}
else
throw std::exception("Invalid put!");
}
//通过中序遍历序列找到根节点
int* rootInorder=startInorder;
while(rootInorder<=endInorder&&*rootInorder!=rootValue)
{
++rootInorder;
}
if(rootInorder==endInorder&&*rootInorder!=rootValue)
{
throw std::exception("Invalid put");
}
int leftLength=rootInorder-startInorder;
int rightLength=endInorder-rootInorder;
int* leftPreorderEnd=startPreorder+leftLength;
if(leftLength>)
{
//递归构建左子树
root->m_pLeft=ConstructCore(startPreorder+,leftPreorderEnd,startInorder,rootInorder-);
}
if(rightLength>)
{
//递归构建右子树
root->m_pRight=ConstructCore(leftPreorderEnd+,endPreorder,rootInorder+,endInorder);
}
return root;
} BinaryTreeNode* Construct(int* preorder,int* inorder,int length)
{
if(preorder==NULL||inorder==NULL||length<=)
{
throw std::exception("Invalid put!");
}
return ConstructCore(preorder,preorder+length-,inorder,inorder+length-);
}
bool DoesTree1HasTree2(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2)
{
if(pRoot2==NULL)
return true;
if(pRoot1==NULL)
return false;
if(pRoot1->m_nValue !=pRoot2->m_nValue)
return false;
return DoesTree1HasTree2(pRoot1->m_pLeft,pRoot2->m_pLeft)&&DoesTree1HasTree2(pRoot1->m_pRight,pRoot2->m_pRight);
}
bool hasSubTree(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2)
{
bool result=false;
if(pRoot1!=NULL&&pRoot2!=NULL)
{
if(pRoot1->m_nValue==pRoot2->m_nValue)
result=DoesTree1HasTree2(pRoot1,pRoot2);
if(!result)
result=hasSubTree(pRoot1->m_pLeft,pRoot2);
if(!result)
result=hasSubTree(pRoot1->m_pRight,pRoot2);
}
return result;
}
void PrintTreeNode(BinaryTreeNode* pNode) {
if(pNode != NULL)
{
printf("value of this node is: %d\n", pNode->m_nValue);
if(pNode->m_pLeft != NULL)
printf("value of its left child is: %d.\n", pNode->m_pLeft->m_nValue);
else
printf("left child is null.\n");
if(pNode->m_pRight != NULL)
printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
else
printf("right child is null.\n");
}
else
{
printf("this node is null.\n");
}
printf("\n");
} //递归打印左右子树
void PrintTree(BinaryTreeNode* pRoot)
{
PrintTreeNode(pRoot);
if(pRoot != NULL)
{
if(pRoot->m_pLeft != NULL)
PrintTree(pRoot->m_pLeft);
if(pRoot->m_pRight != NULL)
PrintTree(pRoot->m_pRight);
}
}
//递归删除左右子树 void DestroyTree(BinaryTreeNode* pRoot)
{
if(pRoot != NULL)
{
BinaryTreeNode* pLeft = pRoot->m_pLeft;
BinaryTreeNode* pRight = pRoot->m_pRight;
delete pRoot;
pRoot = NULL;
DestroyTree(pLeft);
DestroyTree(pRight);
}
} void main()
{
const int length1 = ;
const int length2 = ;
int preorder1[length1] = {, , , , , , , };
int inorder1[length1] = {, , , , , , , };
int preorder2[length2]={,,};
int inorder2[length2]={,,};
BinaryTreeNode *root1 = Construct(preorder1, inorder1, length1);
BinaryTreeNode *root2 =Construct(preorder2, inorder2, length2);
PrintTree(root1);
PrintTree(root2);
if(hasSubTree(root1,root2))
cout<<"hello!"<<endl;
else
cout<<"world!"<<endl;
}
Java代码:
public class IsSubTree {
public static class BinaryTreeNode
{
int m_nValue;
BinaryTreeNode m_pLeft;
BinaryTreeNode m_pRight;
};
public static BinaryTreeNode ConstructBiTree(int[] preOrder,int start,int[] inOrder,int end,int length)
{
//参数验证 ,两个数组都不能为空,并且都有数据,而且数据的数目相同
if (preOrder == null || inOrder == null
|| inOrder.length != preOrder.length || length <= 0) {
return null;
}
int value=preOrder[start];
BinaryTreeNode root=new BinaryTreeNode();
root.m_nValue=value;
root.m_pLeft=root.m_pRight=null;
//递归终止条件:子树只有一个节点
if (length == 1){
if(inOrder[end]==value)
return root;
else
throw new RuntimeException("Invalid input");
}
//分拆子树的左子树和右子树
int i = 0;
while (i < length) {
if (value == inOrder[end - i]) {
break;
}
i++;
}
if(i==length)
throw new RuntimeException("Invalid input");
//建立子树的左子树
root.m_pLeft = ConstructBiTree(preOrder, start + 1, inOrder, end - i - 1, length - 1 - i);
//建立子树的右子树
root.m_pRight = ConstructBiTree(preOrder, start + length - i, inOrder, end, i );
return root;
}
public static boolean DoesTree1HasTree2(BinaryTreeNode pRoot1,BinaryTreeNode pRoot2)
{ //树A存在树B的根节点时,判断B的左右子树是否也存在A树中。
if(pRoot2==null)
return true;
if(pRoot1==null)
return false;
if(pRoot1.m_nValue !=pRoot2.m_nValue)
return false;
return DoesTree1HasTree2(pRoot1.m_pLeft,pRoot2.m_pLeft)&&DoesTree1HasTree2(pRoot1.m_pRight,pRoot2.m_pRight);
}
public static boolean hasSubTree(BinaryTreeNode pRoot1,BinaryTreeNode pRoot2)
{ //判断是否是子树
boolean result=false;
if(pRoot1!=null&&pRoot2!=null)
{
if(pRoot1.m_nValue==pRoot2.m_nValue)
result=DoesTree1HasTree2(pRoot1,pRoot2);//树A存在树B的根节点时,判断B的左右子树是否也存在A树中。
if(!result)
result=hasSubTree(pRoot1.m_pLeft,pRoot2);//在左子树中找B的根节点。
if(!result)
result=hasSubTree(pRoot1.m_pRight,pRoot2);//在右子树中找B的根节点。
}
return result;
}
public static void PrintTreeNode(BinaryTreeNode pNode)
{
if(pNode !=null)
{
System.out.println("the Node is:"+pNode.m_nValue);
if(pNode.m_pLeft != null)
System.out.println( "left child is:"+pNode.m_pLeft.m_nValue);
else
System.out.println("left child is null.\n");
if(pNode.m_pRight != null)
System.out.println("right child is:"+pNode.m_pRight.m_nValue);
else
System.out.println("right child is null.\n");
}
else
{
System.out.println("this node is null.\n");
}
System.out.println();
} //递归打印左右子树
public static void PrintTree(BinaryTreeNode pRoot)
{
PrintTreeNode(pRoot);
if(pRoot !=null)
{
if(pRoot.m_pLeft != null)
PrintTree(pRoot.m_pLeft);
if(pRoot.m_pRight != null)
PrintTree(pRoot.m_pRight);
}
} public static void main(String[] args)
{
int preorder1[] = {1, 2, 4, 7, 3, 5, 6, 8};
int inorder1[] = {4, 7, 2, 1, 5, 3, 8, 6};
int preorder2[]={3,5,6};
int inorder2[]={5,3,6};
BinaryTreeNode root1 = ConstructBiTree(preorder1,0, inorder1,7, preorder1.length);
BinaryTreeNode root2 = ConstructBiTree(preorder2,0, inorder2,2, preorder2.length);
PrintTree(root1);
PrintTree(root2);
if(hasSubTree(root1,root2)
System.out.println("存在子树关系!");
else
System.out.println("不存在子树关系!");
}
}
剑指offer-第三章高质量代码(树的子结构)的更多相关文章
- 剑指offer—第三章高质量代码(数值的整数次方)
高质量的代码:容错处理能力,规范性,完整性.尽量展示代码的可扩展型和可维护性. 容错处理能力:特别的输入和处理,异常,资源回收. 规范性:清晰的书写,清晰的布局,合理的命名. 完整性:功能测试,边界测 ...
- 剑指offer—第三章高质量代码(o(1)时间删除链表节点)
题目:给定单向链表的头指针和一个节点指针,定义一个函数在O(1)时间删除该节点,链表节点与函数的定义如下:struct ListNode{int m_nValue;ListNode* m_pValue ...
- 剑指offer—第三章高质量代码(合并两个排序链表)
题目:输入员两个递增排序的链表,合并这两个链表并使新的链表中的结点仍然是按照递增排序的. 思路:首先,定义两个头节点分别为Head1和Head2的链表,然后比较第一个节点的值,如果是Head1-> ...
- 剑指offer—第三章高质量的代码(按顺序打印从1到n位十进制数)
题目:输入一个数字n,按照顺序打印出1到最大n位十进制数,比如输入3,则打印出1,2,3直到最大的3位数999为止. 本题陷阱:没有考虑到大数的问题. 本题解题思路:将要打印的数字,看成字符串,不足位 ...
- 剑指offer第三章
剑指offer第三章 1.数值的整数次方 给定一个double类型的浮点数base和int类型的整数exponent.求base的exponent次方. class Solution { public ...
- 剑指offer-第三章高质量代码(反转链表)
题目:定义一个函数,输入一个链表的头节点,反转该链表并输出反转链表的头节点. 思路:对一个链表反转需要三个指针操作来保证链表在反转的过程中保证不断链,给链表一个行动指针pNode,对pNode指向的节 ...
- 《剑指offer》第二十六题(树的子结构)
// 面试题26:树的子结构 // 题目:输入两棵二叉树A和B,判断B是不是A的子结构. #include <iostream> struct BinaryTreeNode { doubl ...
- 剑指offer第五章
剑指offer第五章 1.数组中出现次数超过一半的数 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字. 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}.由于数字2在数组 ...
- 剑指offer第七章&第八章
剑指offer第七章&第八章 1.把字符串转换成整数 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数. 数值为0或者字符串不是一个合法的数值则返回0 输入描述: 输入一个字符串 ...
随机推荐
- C3p0的参数
C3p0的参数设置:ComboPooledDataSource和BasicDataSource一样提供了一个用于关闭数据源的close()方法,这样我们就可以保证Spring容器关闭时数据源能够成功释 ...
- Spring Boot 中全局异常处理器
Spring Boot 中全局异常处理器,就是把错误异常统一处理的方法.等价于Springmvc中的异常处理器. 步骤一:基于前面的springBoot入门小demo修改 步骤二:修改HelloCon ...
- Git fetch和git pull的区别, 解决Git报错:error: You have not concluded your merge (MERGE_HEAD exists).
Git fetch和git pull的区别, 解决Git报错:error: You have not concluded your merge (MERGE_HEAD exists). Git fet ...
- CodeChef FORESTGA 二分
Forest Gathering Problem code: FORESTGA Tweet ALL SUBMISSIONS All submissions for this problem ...
- 理解Java中字符流与字节流的区别(转)
1. 什么是流 Java中的流是对字节序列的抽象,我们可以想象有一个水管,只不过现在流动在水管中的不再是水,而是字节序列.和水流一样,Java中的流也具有一个“流动的方向”,通常可以从中读入一个字节序 ...
- mysql升级的一些踩坑点
升级的方法一般有两类: 1.利用mysqldump来直接导出sql文件,导入到新库中,这种方法最省事也最保险 缺点:大库的mysqldump费时费力. 2.直接替换掉 mysql 的安装目录和 my. ...
- TypeScript 教程&手册
参考:https://www.w3cschool.cn/typescript/ https://www.gitbook.com/book/zhongsp/typescript-handbook/det ...
- js中的BOM对象
浏览器对象模型(BOM)以 window 对象为依托,表示浏览器窗口以及页面可见区域.同时, window对象还是 ECMAScript 中的 Global 对象,因而所有全局变量和函数都是它的属性, ...
- Win7性能选项
1. 性能选项:只保留勾选下面的即可. 2. 隐藏explorer导航栏的“库”列表 HKEY_CLASSES_ROOT\CLSID\{031E4825-7B94-4dc3-B131-E946B44C ...
- 四十九 Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)用Django实现搜索结果分页
逻辑处理函数 计算搜索耗时 在开始搜索前:start_time = datetime.now()获取当前时间 在搜索结束后:end_time = datetime.now()获取当前时间 last_t ...