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

    二叉搜索树是一棵二叉树,其中它的每个内部节点都有一个相关的关键字,并有以下附加性质:任意节点中的关键字大于或等于该节点左子树中所有节点含有的关键字,并小于或等于该节点右子树中所有节点含有的关键字。

    二叉搜索树作为符号表的实现基础,可以使得搜索、插入、选择和排序等符号表操作在平均情况下具有最快性能。

    下面程序利用二叉搜索树实现符号表的搜索、插入、构造和计数操作。每个节点包含一个数据项和一个关键字,一个左链接和一个右链接。

     1 template <class Item, class Key>
     2 class ST
     3 {
     4     private:
     5         struct node
     6         {
     7             Item item; node *l, *r;
     8             node (Item x)
     9             { Item = x; l = 0; r = 0;}
    10          };
    11         typedef node *link;
    12         link head;
    13         Item nullItem;
    14         Item searchR(link h, key v)
    15         {
    16             if (h == 0) return nullItem;
    17             Key t = h->item.key();
    18             if (v == t) return h->item;
    19             if (v < t) return searchR(h->l, v);
    20             else return searchR(h->r, v);
    21          }
    22          void insertR(link& h, Item x)
    23          {
    24              if (h == 0) {h = new node(x); return;}
    25              if (x.key() < h->item.key())
    26                  inseartR(h->l, x);
    27              else insertR(h->r, x);
    28           }
    29     public:
    30         ST(int maxN)
    31         {head = 0;}
    32         Item searchR(head, v)
    33         {return searchR(head, v);}
    34         void insert(Item x)
    35         {inseartR(head, x);}
    36 };
  • 相关阅读:
    ABAP Code Inspector那些隐藏的功能,您都知道吗?
    L2-017. 人以群分
    L2-007. 家庭房产
    L2-014. 列车调度
    L2-004. 这是二叉搜索树吗?
    过山车
    hdu 3746 Cyclic Nacklace
    hdu 1867 A + B for you again
    hdu 1686 Oulipo
    Orders
  • 原文地址:https://www.cnblogs.com/ningjing213/p/12778678.html
Copyright © 2011-2022 走看看