看了小甲鱼的视频简直收益多多,完全理解了二叉树的建立及遍历代码,递归的能力太强了,以后一定要多多利用递归呀!!
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
typedef struct node
{
char date;
struct node *lchild;
struct node *rchild;
} BiTNode, *BiTree;
//创建二叉树;
void createBiTree(BiTree &T)
{
char c;
scanf("%c", &c);
if(' ' == c)
T = NULL;
else
{
T = (BiTNode *)malloc(sizeof(BiTNode));
T -> date = c;
createBiTree(T->lchild);
createBiTree(T->rchild);
}
}
//访问二叉树结点;
void visit(char c, int level)
{
printf("%c 位于第 %d层\n", c, level);
}
//前序遍历二叉树,并输出每个节点位于第几层;
void preOrderTraverse(BiTree T, int level)
{
if(T)
{
visit(T->date, level);
preOrderTraverse(T->lchild, level+1);
preOrderTraverse(T->rchild, level+1);
}
}
int main()
{
int level = 1;
BiTree T = NULL;
createBiTree(T);
preOrderTraverse(T, level);
return 0;
}