// test14.cpp : Defines the entry point for the console application. // // test13.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; typedef struct node { char data; struct node * l_child, * r_child; }node,* p_node ; void pre_order(p_node root){ if(root){ cout<<root->data<<" "; pre_order(root->l_child); pre_order(root->r_child); } } p_node advanced_create_tree(char * pre_order,char * mid_order ,int length){ if(!length) return NULL; //长度为0,返回空值 p_node root=new node ; //建立根节点 root->data=* pre_order; char * mid_place=strchr(mid_order,* pre_order); //找到根节点在中根遍历中的位置 if(!mid_place){ cout<<"error happened !"<<endl; return NULL; } int l_length=strlen(mid_order)-strlen(mid_place); //左子树的长度 int r_length=length-l_length-1; //右子树的长度,后面减的1为根节点 root->l_child=advanced_create_tree(pre_order+1,mid_order,l_length); //递归建立根节点的左子树 root->r_child=advanced_create_tree(pre_order+l_length+1,mid_place+1,r_length); //递归建立根节点的右子树 return root; } //通过参数传递的建树算法 void advanced_create_tree(p_node & root,char * pre_order, char * mid_order,int length){ if(!length){ root=NULL; return; //此处的return是必须的,必须得返回,相当于递归中的返回条件!!!! } root=new node; root->data=* pre_order; char * root_place=strchr(mid_order,* pre_order); if(!root_place) cout<<"error happened!"<<endl; int l_length=strlen(mid_order)-strlen(root_place); int r_length=length-l_length-1; advanced_create_tree(root->l_child,pre_order+1,mid_order,l_length); advanced_create_tree(root->r_child,pre_order+l_length+1,root_place+1,r_length); } void destory_tree(p_node& root){ //指针的递归撤销 if(root){ destory_tree(root->l_child); destory_tree(root->r_child); free(root); root=NULL; //前面使用的引用才使得此处对指针有效的赋值!!! } } int count_node(p_node root){//计算总结点数目 if(!root) return 0; if(!root->l_child && !root->r_child) return 1; if(root->l_child && root->l_child) return count_node(root->l_child)+count_node(root->r_child)+1; else if(root->l_child) return count_node(root->l_child)+1; else return count_node(root->r_child)+1; } int count_leaf_node(p_node root){//计算叶子节点数 if(!root) return 0; if(!root->l_child && !root->r_child) return 1; if(root->l_child && root->r_child) return count_leaf_node(root->l_child)+count_leaf_node(root->r_child); else if(root->l_child) return count_leaf_node(root->l_child); else return count_leaf_node(root->r_child); } void main(int argc, char* argv[]) { char pre[] = "abdeijcfg"; char mid[] = "dbiejafcg"; p_node root; advanced_create_tree(root,pre,mid,9); pre_order(root); destory_tree(root); // p_node root=advanced_create_tree(pre,mid,9); pre_order(root); }