根据二叉树的先序遍历建立二叉树

来源:互联网 发布:儿童学唱歌软件 编辑:程序博客网 时间:2024/05/18 12:31
#include<iostream>
#include<queue>
//#include<stdio.h>
using namespace std;
#define Elemtype char 
typedef struct node
{
Elemtype data;
node* left_child;
node* right_child;
}node,*BST;
void build_pre(node*& one_node,queue<Elemtype>& q)//入口这里的指针意思是有意愿在某处建立结点
{
if (q.empty() != true)
{
if (q.front() == '#')
{
one_node = NULL;//这个结点指向空,空不可访问,所以不建立这个节点(子树)
q.pop();
}
else
{
one_node = (node*)malloc(sizeof(node));//造结点建立结点的过程
one_node->data = q.front();
one_node->left_child = NULL;
one_node->right_child = NULL;
q.pop();
build_pre(one_node->left_child, q);//建立左孩子(左子树)
build_pre(one_node->right_child, q);//建立右孩子(右子树)
}
}
}
int main()
{
BST tree = NULL;//指向树的根节点,此时是空树(什么都没有,不存在树)
queue<Elemtype> q;
int n = 0;
cout << "input n" << endl;
cin >> n;
cout << "input nums" << endl;
for (int i = 0; i < n; i++)
{
Elemtype temp;
cin >> temp;
q.push(temp);
}
build_pre(tree, q);
return 0;
}
阅读全文
0 0