目录
一、二叉树的基本概念
性质1:二叉树第i层上的结点数目最多为2i-1(i>=1)
性质2:深度为k的二叉树至多有2k-1个结点(k>=1)
性质3:包含n个结点的二叉树的高度至少为(log2n)+1
性质4:在任意一棵二叉树中,若终端结点的个数为n0,度为2的结点数为n2,则n0=n2+1
二、二叉树的存储结构
三、二叉树的建立与遍历
二叉树的深度优先遍历(dfs):先序遍历、中序遍历、后序遍历
二叉树的宽度优先遍历(bfs):层序遍历
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
typedef struct node{
char val;
struct node* left;
struct node* right;
}*BT,BTnode;
void create(BT &T) //二叉树的先序建立
{
char c;
cin>>c;
if(c=='#')T=NULL;
else{
T=new BTnode();
T->val=c;
create(T->left);
create(T->right);
}
}
void post(BT T)//二叉树的后序遍历
{
if(T!=NULL){
post(T->left);
post(T->right);
cout<<T->val;
}
}
void level(BT T)//层序遍历
{
if(T==NULL)return;
queue<BT>q;
q.push(T);
while(!q.empty()){
BT c=q.front();
q.pop();
cout<<c->val;
if(c->left!=NULL){
q.push(c->left);
}
if(c->right!=NULL){
q.push(c->right);
}
}
}
int treeheight(BT T)
{
if(T==NULL)return 0;
else{
int left=treeheight(T->left);
int right=treeheight(T->right);
return max(left,right)+1;
}
}
int main()
{
BT T;
//1.二叉树的建立(先序)
create(T);
cout<<"后序遍历:";
//2.二叉树的遍历(后序)
post(T);
cout<<endl;
//二叉树的遍历(层序bfs)
cout<<"层序遍历:";
level(T);
cout<<endl;
//二叉树的高度
cout<<treeheight(T)<<endl;
return 0;
}