博前感想:
二叉树也是数据结构中非常中非常重要的一种结构,特别是在当前大数据的时候,二叉树的存储和查找排序算法显得尤为重要。
下面是代码块:
#include<stdio.h>
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
using namespace std;
typedef struct Node
{
Node *lc, *rc;
char data;
}node,*binary_tree;
void create(binary_tree &h)
{
char ch;
cin >> ch;
if (ch == '%')
{
h = NULL;
}
else
{
h = new Node;
h->data = ch;
create(h->lc);
create(h->rc);
}
}
void preorder(binary_tree h)
{
if (h)
{
cout << h->data<<" ";
preorder(h->lc);
preorder(h->rc);
}
//cout << endl;
}
int get_depth(binary_tree h)
{
if (h == NULL)
{
return 0;
}
int l_depth = 1 + get_depth(h->lc);
int r_depth = 1 + get_depth(h->rc);
int max_depth = l_depth > r_depth ? l_depth : r_depth;
return max_depth;
}
int get_leaves(binary_tree h)
{
if(h==NULL) //顺序不能换
{
return 0;
}
if (h->lc == NULL && h->rc == NULL)
{
return 1;
}
return get_leaves(h->lc) + get_leaves(h->rc);
}
int get_nodenum(binary_tree h) //获取总的节点数
{
if (h == NULL)
{
return 0;
}
//if (h != NULL)//&&(h->lc!=NULL||h->rc!=NULL))
//{
// return 1;
//}
return get_nodenum(h->lc) + get_nodenum(h->rc)+1;
}
int get_mid_nodenum(binary_tree h) //获取中间节点数
{
get_nodenum(h);
get_leaves(h);
//int mid_node_sum;
//if (h == NULL)
//{
// return 0;
//}
//if (!(h->lc == NULL && h->rc == NULL))
//{
//
//}
get_mid_nodenum(h->lc)++;
get_mid_nodenum(h->rc)++;
int l_mid_node_num = get_mid_nodenum(h->lc) ;
int r_mid_node_num = get_mid_nodenum(h->rc) ;
= l_mid_node_num + r_mid_node_num+1 ;
//return get_mid_nodenum(h->lc) + get_mid_nodenum(h->rc);
return get_nodenum(h) - get_leaves(h);
}
void mirror(binary_tree h)
{
if (h == NULL)
{
return;
}
binary_tree t = h->lc;
h->lc = h->rc;
h->rc = t;
mirror(h->lc);
mirror(h->rc);
}
int main()
{
binary_tree hwq;
create(hwq);
cout << "先序遍历为:" << endl;
preorder(hwq);
cout << endl;
cout <<"叶子数为:" << get_leaves(hwq) <<endl;
cout << "树的深度为:" << get_depth(hwq) << endl;
cout << "节点数为:" << get_nodenum(hwq) << endl;
cout << "中间节点数为:" << get_mid_nodenum(hwq) << endl;
mirror(hwq);
cout << "镜像后的二叉树先序遍历为:" << endl;
preorder(hwq);
cout << endl;
system("pause");
return 0;
}
涉及二叉树的算法不少而且有的也很复杂,我自己的水平有限,所以就不为大家一一介绍了。大家有兴趣也可以去我一个毕业学长的网站上去看。