您的位置:首页 > 其它

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

2017-11-11 14:32 197 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: