一、树的一些术语、操作
1、根节点,叶子节点,左孩子,右孩子,双亲;
2、满二叉树、完全二叉树、线索二叉树;
3、二叉树的5个性质:二叉树五大特性;
4、遍历:先序遍历(DLR),中序遍历(LDR),后序遍历(LRD);
5、常用操作:递归,返回指针、int;
6、用最简单的例子写算法,简单例子能用,复杂的就也能用;
二、二叉树的遍历算法
1、节点存储结构:
struct binode
{
char ch;
binode* lchild;
binode* rchild;
};
2、算法代码
#include<iostream>
#include<string>
using namespace std;
#include<queue>;
#define ok 1
#define error -1
struct binode
{
char ch;
binode* lchild;
binode* rchild;
};
binode* creatbitree(binode* t) // 创建二叉树,以‘#’表示空指针;DLR遍历
{
cout << "请输入字符:" << endl;
char ch;
cin >> ch;
if (ch == '#')
{
return NULL;
}
t = new binode; // DLR
t->ch = ch;
t->lchild = creatbitree(t->lchild);
t->rchild = creatbitree(t->rchild);
return t;
}
int previsit(binode* t) //前序遍历
{
if (t == NULL)
{
return ok;
}
cout << t->ch;
previsit(t->lchild);
previsit(t->lchild);
return ok;
}
int invisit(binode* t) //中序遍历
{
if (t == NULL)
{
return ok;
}
invisit(t->lchild);
cout << t->ch;
invisit(t->lchild);
return ok;
}
int backvisit(binode* t) //后序遍历
{
if (t == NULL)
{
return ok;
}
backvisit(t->lchild);
backvisit(t->lchild);
cout << t->ch;
return ok;
}
int levelvisit(binode* t) //层次遍历,用队列的概念
{
if (t == NULL)
{
return 0;
}
else
{
queue<binode*> q;
q.push(t);
while (!q.empty())
{
if (q.front()->lchild != NULL)
{
q.push(q.front()->lchild);
}
if (q.front()->rchild != NULL)
{
q.push(q.front()->rchild);
}
cout << q.front()->ch;
q.pop();
}
return ok;
}
}
binode* copy(binode* t) //dlr 拷贝算法
{
if (t = NULL)
{
return NULL;
}
binode* c_t = new binode;
c_t->ch = t->ch;
c_t->lchild = copy(t->lchild);
c_t->rchild = copy(t->rchild);
return c_t;
}
int depth(binode* t) // 求深度
{
if (t == NULL)
{
return 0;
}
int m = depth(t->lchild); //左子树深度
int n = depth(t->rchild); //右子树深度
if (m > n)
{
return m + 1;
}
else
{
return n + 1;
}
}
int nodecount(binode* t) //求节点总数,左加右加根
{
if (t == NULL)
{
return 0;
}
return nodecount(t->lchild) + nodecount(t->rchild) + 1;
}
int leafcount(binode* t) //求叶子节点
{
if (t == NULL)
{
return 0;
}
if (t->lchild == NULL && t->rchild == NULL)
{
return 1;
}
return leafcount(t->lchild) + leafcount(t->rchild);
}