码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树树 from ZZJ

时间:2018-11-20 23:01:04      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:--   post   creat   span   str   from   code   while   include   

#include<stdio.h>
#include <stdlib.h>
typedef struct Bitnode {
    int val;
    struct Bitnode *left;
    struct Bitnode *right;
}Bitnode;
Bitnode *CreatBitree_level()
{
    int front = 1, rear = 0, x;
    struct Bitnode *q[1234], *t, *root = NULL;
    while(scanf("%d",&x),x != -1)
    {
        if(x == 0)
            t=NULL;
        else
        {
            t = (Bitnode *)malloc(sizeof(Bitnode));
            t->val = x;
            t->right = NULL;
            t->left = NULL;
        }

        q[++rear] = t;
        if(rear == 1)
            root = t;
        else
        {
            if(t && q[front])
            {
                 ( rear%2 == 0 )? (q[front]->left = t):(q[front]->right = t);
                 //加到左子树 或 右子树
            }
            if(rear % 2 == 1)
                front++;
        }
    }
    return root;
}
int s = 0;
void dfs(struct Bitnode *rt,int ans){
    s = ans > s ? ans : s;
    if(!rt) return;
    dfs(rt->left,ans+1);
    dfs(rt->right,ans+1);
}
int depth(struct Bitnode *rt){
    s = 0;
    dfs(rt,0);
    return s;
}//求树高

void preorder(struct Bitnode *rt){
    if(!rt) return ;
    printf(" %d",rt->val);
    preorder(rt->left);
    preorder(rt->right);
}

void inorder(struct Bitnode *rt){
    if(!rt) return;
    inorder(rt->left);
    printf(" %d",rt->val);
    inorder(rt->right);
}

void postorder(struct Bitnode *rt){
    if(!rt) return;
    postorder(rt->left);
    postorder(rt->right);
    printf(" %d",rt->val);
}

int main()
{
    Bitnode *t;
    int n;
    scanf("%d",&n);
    while(n--)
    {
        t = CreatBitree_level();
        printf("%d",depth(t));
        inorder(t);
        printf("\n");
    }
    return 0;
}

 

二叉树树 from ZZJ

标签:--   post   creat   span   str   from   code   while   include   

原文地址:https://www.cnblogs.com/Kingpenguin/p/9991733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!