• 由先序遍历序列和中序遍历序列恢复二叉树以及统计叶子节点个数和树的深度


     1 #include <fstream>
     2 #include <iostream>
     3 
     4 using namespace std;
     5 
     6 struct node
     7 {
     8     char c;
     9     struct node *lch,*rch;
    10 };
    11 
    12 int count_leaf(node* tree);//统计叶子结点
    13 int count_deep(node* tree);//统计树的深度
    14 void create_tree(char* l,char* r,int i,int j,int e,int f,node** tree);//由先序遍历序列和中序遍历序列恢复二叉树
    15 
    16 int main()
    17 {
    18     //freopen("D:\input.in","r",stdin);
    19     //freopen("D:\output.out","w",stdout);
    20     node *tree;
    21 char pre[]="ABDGCEF"; 22 char in[]="DGBAECF"; 23 create_tree(pre,in,0,6,0,6,&tree); 24 cout<<count_leaf(tree)<<endl; 25 cout<<count_deep(tree)<<endl; 26 return 0; 27 } 28 int count_leaf(node* tree) 29 { 30 if(tree==NULL) return 0; 31 if(tree->lch==NULL&&tree->rch==NULL) return 1; 32 return count_leaf(tree->lch)+count_leaf(tree->rch); 33 } 34 int count_deep(node* tree) 35 { 36 if(tree==NULL) return 0; 37 return 1+max(count_deep(tree->lch),count_deep(tree->rch)); 38 } 39 void create_tree(char* l,char* r,int i,int j,int e,int f,node** tree) 40 { 41 int m; 42 (*tree)=new node; 43 (*tree)->c=l[i]; 44 m=e; 45 while(r[m]!=l[i]) m++; 46 if(m==e) (*tree)->lch=NULL; 47 else create_tree(l,r,i+1,i+m-e,e,m-1,&(*tree)->lch); 48 if(m==f) (*tree)->rch=NULL; 49 else create_tree(l,r,i+m-e+1,j,m+1,f,&(*tree)->rch); 50 }
  • 相关阅读:
    centos7 rabbitmq系统部署
    socket粘包、断包、校验
    C#对象、文件与二进制串(byte数组)之间的转换
    Windows Error Code
    C#之Socket断线和重连
    BitConverter 整数和十六进制互转
    DateTime还是DateTimeOffset?Now还是UtcNow?
    WebAPI 跨域
    Console Owin 跨域解决
    2019.12.17 Arcgis10.1许可到期解决方法
  • 原文地址:https://www.cnblogs.com/jiu0821/p/4127207.html
Copyright © 2020-2023  润新知