二叉树的定义:每个结点至多只有两颗子树(即二叉树中不存在度大于2的结点),并且二叉树的子树有左右之分,其次序不能任意颠倒。
思维导图:
结构体:
在定义结构体时候,需要定义三个指针,left为左指针,right为右指针,parent为父节点的指针
typedef struct Btree
{
int data;
struct Btree * left;
struct Btree * right;
struct Btree * parent;
}* Bnode;
基础的函数的声明:
-
CreateBnode() 是用于创建二叉树的总函数
-
DFBtree() 为递归函数,用于插入新的节点
-
CreateF() 在将二叉树创建完成后,通过该函数将他们的父节点挂在parent对应的指针上
-
print() 函数用于将二叉树遍历,其中遍历右分为中序遍历等多种遍历方式
Bnode CreateBnode(Bnode T);
void print(Bnode T);
Bnode DFBtree(Bnode T , Btree * s);
void CreateF(Bnode T);
1.创建二叉树:
输入序列,以-1为结束标识符
Bnode CreateBnode(Bnode T)
{
Bnode s = NULL;
int key = 0;
cout << "Please enter your keywords , end with -1!" << endl;
while(1)
{
cin >> key;
if(key == -1)
break;
s = new Btree;
s -> data = key