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

    VonGang原创,转载请注明:http://www.cnblogs.com/vongang/

    二叉排序数的(递归)定义:1、若左子树非空,则左子树所有节点的值均小于它的根节点;2、若右子树非空,则右子树所有节点的值均大于于它的根节点;3、左右子树也分别为二叉排序树。

    如图:

    链表实现(比较简单):

    View Code
    #include <stdio.h>
    #include
    <malloc.h>

    typedef
    struct node
    {
    int data;
    struct node * lchild;
    struct node * rchild;
    }node;

    void Init(node *t)
    {
    t
    = NULL;
    }

    node
    * Insert(node *t , int key)
    {
    if(t == NULL)
    {
    node
    * p;
    p
    = (node *)malloc(sizeof(node));
    p
    ->data = key;
    p
    ->lchild = NULL;
    p
    ->rchild = NULL;
    t
    = p;
    }
    else
    {
    if(key < t->data)
    t
    ->lchild = Insert(t->lchild, key);
    else
    t
    ->rchild = Insert(t->rchild, key);
    }
    return t; //important!
    }

    node
    * creat(node *t)
    {
    int i, n, key;
    scanf(
    "%d", &n);
    for(i = 0; i < n; i++)
    {
    scanf(
    "%d", &key);
    t
    = Insert(t, key);
    }
    return t;
    }

    void InOrder(node * t) //中序遍历输出
    {
    if(t != NULL)
    {
    InOrder(t
    ->lchild);
    printf(
    "%d ", t->data);
    InOrder(t
    ->rchild);
    }
    }

    int main()
    {
    node
    * t = NULL;
    t
    = creat(t);
    InOrder(t);
    return 0;
    }

    数组实现(这个有意思):

    定义left[], right[]作为标记,记录但前节点是哪个点的左(右)孩子

    比如我们要对 4,3, 8,6,1。排序排好序后的二叉树如图:

    把这个过程在纸上用笔走一遍,你就会一目了然。

    My Code:

    #include <stdio.h>
    #include
    <string.h>
    #define N 1000

    int l[N], r[N], key[N], flag, root;

    void insert(int index, int x)
    {
    if(x <= key[index])
    {
    if(l[index] == -1) l[index] = flag;
    else insert(l[index], x);
    }
    else
    {
    if(r[index] == -1) r[index] = flag;
    else insert(r[index], x);
    }
    }
    void InOrder(int index)
    {
    if(l[index] != -1) InOrder(l[index]);
    printf(
    "%d ", key[index]);
    if(r[index] != -1) InOrder(r[index]);
    }

    int main()
    {
    int i, x, n;
    memset(l,
    -1, sizeof(l));
    memset(r,
    -1, sizeof(r));

    scanf(
    "%d", &n);
    root
    = -1;
    flag
    = 0;

    for(i = 0; i < n; i++)
    {
    scanf(
    "%d", &x);
    if(root == -1) key[++root] = x;
    else
    {
    key[
    ++flag] = x;
    insert(root, x);
    }
    }
    InOrder(root);
    return 0;
    }
  • 相关阅读:
    安装WebStorm
    Could not obtain transaction-synchronized Session
    Hibernate4 No Session found for current thread原因
    Spring3系列7- 自动扫描组件或Bean
    论坛角色
    firefox浏览器无法显示bootstrap图标问题总结
    express文件上传中间件Multer最新使用说明
    判断圆和矩形是否相交C
    转化为用欧几里得算法判断互质的问题D
    (记录前面算过的后面仍然会用的数减小复杂度)A
  • 原文地址:https://www.cnblogs.com/vongang/p/2143224.html
Copyright © 2011-2022 走看看