#include "iostream" /* 输入:ABC DE G F ABC DE G F */ #include "bits/stdc++.h" using namespace std; typedef struct bitnode { char data; bitnode *lchild,*rchild; } *bintree; bintree creatree(bintree &root)//先序创建树 { char a=getchar(); if(a==' ') { root=NULL; return root; } else { root=(bintree)malloc(sizeof(bitnode)); root->data=a; creatree(root->lchild); creatree(root->rchild); return root; } } void PreOrderTraverse(bintree root)//InOrderTraverse中序 PostOrderTraverse 倒序 { if(root==NULL) { return ; } else { PreOrderTraverse(root->lchild); PreOrderTraverse(root->rchild); cout<<root->data<<' '; } } int CountDegreeOne(bintree root)//度为一节点的个数 { if(root==NULL) return 0; else { int a=CountDegreeOne(root->lchild); int b=CountDegreeOne(root->rchild); if(root->lchild&&!root->rchild||root->rchild&&!root->lchild) return a+b+1; else return a+b; } } int DeepTree(bintree root)//树的深度 { if(root==NULL) return 0; else { int a=DeepTree(root->lchild); int b=DeepTree(root->rchild); if(a>=b) return a+1; else return b+1; } } int same(bintree root,bintree root1)//判断两棵树是否相同 { if(root&&!root1||root1&&!root||!root&&!root1) { return 0; } else { if(root->data==root1->data) { int a=same(root->lchild,root1->lchild); int b=same(root->rchild,root1->rchild); if(a==b==1) return 1; } else return 0; } } int main() { bintree root; bintree root1; creatree(root); getchar(); creatree(root1); PreOrderTraverse(root); cout<<endl<<"树的深度为:"<<DeepTree(root)<<endl; cout<<endl<<"树的度为一的个数:"<<CountDegreeOne(root)<<endl; if(same(root,root1)) cout<<"相同"<<endl; else cout<<"different"<<endl; return 0; }
树的各类基本操作(数据结构)
猜你喜欢
转载自blog.csdn.net/weixin_41466575/article/details/84350918
今日推荐
周排行