zoukankan      html  css  js  c++  java
  • PE: 行末不留空格 BST 插入与遍历

    PE了一早上——就是因为行末空格的问题

    想过用链表在遍历过程中存储节点,然后打印;

    想过用静态变量保存;

    最后,回到了指针,传递计数器的地址。

    View Code
    //1005 BST 建树、遍历
    # include <stdio.h>
    # include <stdlib.h>

    typedef struct Tnode{
    int key;
    struct Tnode *left;
    struct Tnode *right;
    }node;

    node *BST_insert(node *root, node *p);
    void preorder(node *x, int *p);
    void inorder(node *x, int *p);
    void aftorder(node *x, int *p);

    int main()
    {
    int T, n, cnt, tmp;
    node *p, *root;
    scanf("%d", &T);
    while (T > 0)
    {
    root = NULL;
    scanf("%d", &n);
    tmp = cnt = n;
    while (n > 0)
    {
    p = (node *)malloc(sizeof(node));
    p->left = p->right = NULL;
    scanf("%d", &p->key);
    root = BST_insert(root, p);
    --n;
    }
    preorder(root,&cnt);
    printf("\n");
    cnt = tmp;
    inorder(root,&cnt);
    printf("\n");
    cnt = tmp;
    aftorder(root,&cnt);
    printf("\n\n");
    --T;
    }
    return 0;
    }

    node *BST_insert(node *root, node *p)
    {
    node *x, *y;
    y = NULL;
    x = root;
    while (x != NULL)
    {
    y = x;
    if (p->key < x->key) x = x->left;
    else x = x->right;
    }
    if (y == NULL) root = p;
    else if (p->key < y->key)
    y->left = p;
    else y->right = p;
    return root;
    }
    void preorder(node *x, int *p)
    {
    if (x != NULL)
    {
    printf(((*p)==1 ? "%d":"%d "), x->key);
    --(*p);
    preorder(x->left, p);
    preorder(x->right, p);
    }
    }
    void inorder(node *x, int *p)
    {
    if (x != NULL)
    {
    inorder(x->left, p);
    printf(((*p)==1 ? "%d":"%d "), x->key);
    --(*p);
    inorder(x->right, p);
    }
    }
    void aftorder(node *x, int *p)
    {
    if (x != NULL)
    {
    aftorder(x->left, p);
    aftorder(x->right, p);
    printf(((*p)==1 ? "%d":"%d "), x->key);
    --(*p);
    }
    }

    欢迎、谢谢大牛的指正!

  • 相关阅读:
    PHP之防御sql注入攻击的方式
    分享Java开发的利器-Lombok
    Linux最佳的云存储服务分析
    提升PHP编程效率的20个要素
    Java中常见的URL问题及解决方案
    配置CNPM-基础案例
    微软Skype Linux客户端全新发布
    jQuery 3.0最终版发布,十大新特性眼前一亮
    【风马一族_mysql】MySQL免安装版环境配置图文教程
    【风马一族_物理】维度空间的粒子
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2355626.html
Copyright © 2011-2022 走看看