二叉树建立方法:
一、我们要明确的一点是只有中序是无法创建二叉树的,它要结合先序,两者相联系才可以。
二、根据二叉树的图,得出先序的顺序是ABDECFG,而与此同时的中序DBEAFCG,根据这个建立。
三、然后就是要根据二叉树的原则编写代码,你要知道的是前序遍历序列中的首元素是二叉树的根节点。
四、然后你要做的是在中序遍历序列中找到这个节点,他是中间的分水岭,前面其左节点,后面是右节点。
五、最后要做的是建立根节点的左子树和右子树,再由中序 遍历序列中根节点的位置确定我们前面提到的子树的节点,这样二叉树就差不多建立完成了。
创建二叉树的源程序如下:
#include <cstdlib>
#include <stdio.h>
typedef struct node
{ //树的结点
int data
struct node* left
struct node* right
} Node
typedef struct
{ //树根
Node* root;
} Tree
void insert(Tree* tree, int value)//创建树
{
Node* node=(Node*)malloc(sizeof(Node))//创建一个节点
node->data = value
node->left = NULL
node->right = NULL
if (tree->root == NULL)//判断树是不是空树
{
tree->root = node
}
else
{//不是空树
Node* temp = tree->root//从树根开始
while (temp != NULL)
{
if (value <temp->data)//小于就进左儿子
{
if (temp->left == NULL)
{
temp->left = node
return
}
else
{//继续判断
temp = temp->left
}
}
else {//否则进右儿子
if (temp->right == NULL)
{
temp->right = node
return
}
else {//继续判断
temp = temp->right
}
}
}
}
return;
}
void inorder(Node* node)//树的中序遍历
{
if (node != NULL)
{
inorder(node->left)
printf("%d ",node->data)
inorder(node->right)
}
}
int main()
{
Tree tree
tree.root = NULL//创建一个空树
int n
scanf("%d",&n)
for (int i = 0i <ni++)//输入n个数并创建这个树
{
int temp
scanf("%d",&temp)
insert(&tree, temp)
}
inorder(tree.root)//中序遍历
getchar()
getchar()
return 0
}
扩展资料:
简单二叉树定义范例:此树的顺序结构为:ABCDE
#include <cstdlib>
#include <stdio.h>
#include <string>
int main()
{
node* p = newnode
node* p = head
head = p
string str
cin >>str
creat(p, str, 0)//默认根结点在str下标0的位置
return 0
}
//p为树的根结点(已开辟动态内存),str为二叉树的顺序存储数组ABCD##E或其他顺序存储数组,r当前结点所在顺序存储数组位置
void creat(node* p, string str, int r)
{
p->data = str[r]
if (str[r * 2 + 1] == '#' || r * 2 + 1 >str.size() - 1)p->lch = NULL;
else
{
p->lch = newnode
creat(p->lch, str, r * 2 + 1)
}
if (str[r * 2 + 2] == '#' || r * 2 + 2 >str.size() - 1)p->rch = NULL
else
{
p->rch = newnode
creat(p->rch, str, r * 2 + 2)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)