zoukankan      html  css  js  c++  java
  • 二叉树

    #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("
    ");
        }
        return 0;
    }
  • 相关阅读:
    NOIP 2017逛公园(记忆化搜索)
    NOIP 2012疫情控制 (二分+倍增+贪心)
    NOIP 2005过河(DP+路径压缩)
    P1198 [JSOI2008]最大数
    [Noip2016]蚯蚓
    [六省联考2017]期末考试
    六省联考:组合数问题
    蒜头君的兔子
    bzoj1015 [JSOI2008]星球大战starwar
    luogu P3370 【模板】字符串哈希
  • 原文地址:https://www.cnblogs.com/Kingpenguin/p/9991733.html
Copyright © 2011-2022 走看看