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

    欢迎、谢谢大牛的指正!

  • 相关阅读:
    LeetCode 172. Factorial Trailing Zeroes
    C++primer 练习12.27
    C++primer 练习12.6
    C++primer 练习11.33:实现你自己版本的单词转换程序
    77. Combinations
    75. Sort Colors
    74. Search a 2D Matrix
    73. Set Matrix Zeroes
    71. Simplify Path
    64. Minimum Path Sum
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2355626.html
Copyright © 2011-2022 走看看