首页 > 编程知识 正文

建立二叉树的代码,二叉树的深度算法实现

时间:2023-05-04 13:46:46 阅读:166786 作者:3721

完全二叉树的定义:具有深度为k的n个节点的二叉树,按从上到下、从左到右的顺序对树中的节点编号。 当编号I(1In )的节点与完全二叉树中编号I的节点的二叉树位置相同时,我们将此二叉树称为完全二叉树。

因此,判断完全二叉树需要满足两个条件。

1所有叶子节点处的深度为二叉树的深度

2不存在只有右边的孩子而没有孩子的节点

求深度就行了。 主要是递归地稍微转一下

递归一次,深度加1,返回一次,深度减1

# includeiostreamusingnamespacestd; # defineelemtypecharstructbitree { elemtype data; BiTree* Lchild,* Rchild; (; voidcreatebitree(bitree*t ) {ElemType temp; temp=getchar (; if(temp=='# ' ) {T=NULL; }else{T=new BiTree; T-data=temp; 创建bitree (t-lchild ); createbitree(t-rchild ); }voidinorder(bitree*t ) if ) t ) inorder ) t-lchild ); cout T-data; inorder(t-rchild ); }voiddeepth(bitree*t,int {temp,int n ) if ) t ) temp; EEPTH(t-lchild,temp,n ); EEPTH(t-Rchild,temp,n ); }else{if(tempn ) n=temp; temp----; }voidisbest(bitree*t,int n,int {temp,bool temp1) if ) t ) temp; if(t-lchild==nullt-rchild!=null(temp1=false; isbest(t-lchild,temp,n,temp1); isbest(t-rchild,temp,n,temp1); (else ) if )时间!=n ) temp1=false; temp----; }}int main () {BiTree* T; bool temp1=true; T=NULL; int temp,n; temp=0; n=0; createbitree(t; 在inorder(t; EEPTH(t,temp,n ); temp=0; cout n; isbest(t,n,temp,temp1); if (! temp1) cout 'no ); elsecout 'yes '; 返回0; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。