- 代码如下
//
// main.cpp
// test
//
// Created by 梁亚宾 on 16/6/4.
// Copyright © 2016年 liang. All rights reserved.
//
//#include <iostream>
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
///前序创建
void CreateBiTree(BiTree *T) {
char c;
scanf("%c",&c);
if (c == ' ') {
*T = NULL;
}else{
*T = (BiTNode *)malloc(sizeof(BiTNode));///创建一个 树
(*T)->data =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->data,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;
}
个人博客: www.liangtongzhuo.com