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);
    }
    }

    欢迎、谢谢大牛的指正!

  • 相关阅读:
    1105 Spiral Matrix (25分)(蛇形填数)
    1104 Sum of Number Segments (20分)(long double)
    1026 Table Tennis (30分)(模拟)
    1091 Acute Stroke (30分)(bfs,连通块个数统计)
    1095 Cars on Campus (30分)(排序)
    1098 Insertion or Heap Sort (25分)(堆排序和插入排序)
    堆以及堆排序详解
    1089 Insert or Merge (25分)
    1088 Rational Arithmetic (20分)(模拟)
    1086 Tree Traversals Again (25分)(树的重构与遍历)
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2355626.html
Copyright © 2011-2022 走看看