二叉树的建立和遍历
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}Node;
void buildTree(Node *&node)
{
char data;
scanf("%c",&data);
if(data=='#') //如果输入的是'#',则该节点为NULL
{
node=NULL;
return;
}
else
{
node=new Node;
node->data=data;
buildTree(node->lchild); //递归地构建左子树
buildTree(node->rchild); //递归地构建右子树
return;
}
}
void preOrder(Node *root)
{
if(root)
{
cout<<root->data;
preOrder(root->lchild);
preOrder(root->rchild);
}
}
int main()
{
Node *root;
buildTree(root); //样例输入:124##5##3##
preOrder(root); //前序遍历输出:12453
return 0;
}
人生如修仙,岂是一日间。何时登临顶,上善若水前。
浙公网安备 33010602011771号