2018.9.19(二叉树)

链表表示

题目描述:用链表建立二叉树。
有一棵深度为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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值