博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
树的子结构
阅读量:7063 次
发布时间:2019-06-28

本文共 1644 字,大约阅读时间需要 5 分钟。

 

面试题目:输入两颗二叉树A,B,判断B是不是A的子结构;

#include 
#include
using namespace std;typedef struct BinaryTreeNode{ int value; BinaryTreeNode * lchild; BinaryTreeNode *rchild;}BinaryTreeNode;typedef BinaryTreeNode * BiTree;void CreateBiTreeByLevel(BiTree &t,int Array[],int i,int len){ if(Array[i]==0||i > len) return; t = new BinaryTreeNode; t->value = Array[i]; t->lchild = NULL; t->rchild = NULL; CreateBiTreeByLevel(t->lchild,Array,2*i,len); CreateBiTreeByLevel(t->rchild,Array,2*i+1,len);}void display(BiTree *t) //显示树形结构 { if(*t!=NULL) { cout<<(*t)->value; if((*t)->lchild!=NULL) { cout<<'('; display(&(*t)->lchild); } if((*t)->rchild!=NULL) { cout<<','; display(&(*t)->rchild); cout<<')'; } }}bool ifTheSameTree(BiTree &t1,BiTree &t2){ if (t2 == NULL)return true;//B树为空,肯定是相同的树 if(t1 == NULL)return false; if (t1->value!=t2->value)return false;//节点不同,不是 else { return ifTheSameTree(t1->lchild,t2->lchild) & ifTheSameTree(t1->rchild,t2->rchild);//左右均为true返回true }}bool isSubBinTree(BiTree &t1,BiTree &t2){ bool result = false; if(t1 != NULL && t2 != NULL) { if (t1->value == t2->value)//根节点相同,就判断A,B树是否一样 { result = ifTheSameTree(t1,t2); } if(!result)result = isSubBinTree(t1->lchild,t2);//判断左子树 if (!result) result = isSubBinTree(t1->rchild,t2);//判断右子树 } return result;}int main(){ BiTree A,B; //InitBiTree(&T); int a[14] = {0,1,2,3,4,5,6,0,0,0,7,0,8,9};//从下标1开始,0标识没有节点 int b[4] = {0,6,8,9}; CreateBiTreeByLevel(A,a,1,13); CreateBiTreeByLevel(B,b,1,2); display(&A); display(&B); if(isSubBinTree(A,B))cout<<"B is A subTree"; else cout<<"B is Not A subTree"; system("pause");}

 

来源:

转载地址:http://cunll.baihongyu.com/

你可能感兴趣的文章
Eureka微服务实战-服务提供者
查看>>
简单的原生ajax
查看>>
h5开发坑点小总结
查看>>
几分钟内提升技能的8个 JavaScript 方法!
查看>>
mac显示隐藏文件
查看>>
Android 插件化原理-好文收集(陆续中。。。)
查看>>
双亲委派模型与Tomcat类加载架构
查看>>
Highcharts tooltip显示数量和百分比
查看>>
小程序兼容iphoneX(齐刘海)代码,mpvue的写法
查看>>
小米设备怎么不ROOT激活Xposed框架的步骤
查看>>
Vue Router
查看>>
你所听到的技术原理、技术本质到底是什么?
查看>>
决战燕京城-10 前往天寿山
查看>>
WebMvcTest与SpringBootTest
查看>>
面试官:你接受免费加班吗?程序员这样怼回去,网友:老铁没毛病
查看>>
分享我的个人项目:Wildfire 野火评论系统
查看>>
【机器视觉与图像处理】基于MATLAB的角度计算
查看>>
一篇很全面的IOS面试题(下)
查看>>
极简.高性能.分布式框架,可运行于多种环境(apache/php-fpm,swoole)
查看>>
DESTOON7.0农产品B2B供应求购交易平台源码
查看>>