链表表示
题目描述:用链表建立二叉树。
有一棵深度为N(N<=20)的树,请用链表建立二叉树。
【输入格式】
第一行为一正整数N,表示有多少个元素,第二行为N个元素
【输出格式】
按数组顺序输出即可。
【输入样例】
9
6 3 8 5 2 9 4 7 10
【输出样例】
6 3 2 5 4 8 7 9 10
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct Tree
{
Tree *left,*right;
int data;
Tree *next;
};
Tree *Insert(Tree *root,int node)
{
Tree *new_node,*current_node,*parent_node;
new_node=(Tree *)malloc(sizeof(Tree));
new_node->data=node;
new_node->left=NULL;
new_node->right=NULL;
if(root==NULL)//第一个节点建立
return new_node;
current_node=root;//存储当前节点
while(current_node!=NULL)
{
parent_node=current_node;//存储父节点
current_node=(node>current_node->data)?current_node->right:current_node->left;//判读其为左子树还是右子树,灵活运用三目运算符;
}
if(node>parent_node->data)
parent_node->right=new_node;
else
parent_node->left=new_node;
return root;
}
Tree *Create(int *node,int len)
{
Tree *root=NULL;
for(int i=1;i<=len;i++)
root=Insert(root,node[i]);
return root;
}
void print(Tree *root)//递归打印二叉树
{
if(root!=NULL)
{
printf("%d ",root->data);
print(root->left);
print(root->right);
}
}
int main()
{
int N;
while(cin>>N)
{
Tree *root=NULL;
int node[N+1];
for(int i=1;i<=N;i++)
cin>>node[i];
root=Create(node,N);
print(root);
printf("\n");
}
return 0;
}