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

    算法导论笔记:

    每个节点保存的数据:key,卫星数据,left,right,p //左孩子,右孩子,父节点

    struct Nod{
          int key;
          Nod* left=NULL,right=NULL,p=NULL;
    };

    中序遍历得到所有关键字的按序输出:

    void inorder_tree_walk(Nod* x)
    {
          if(x!=NULL){
               inorder_tree_walk(x->left);
               cout<<x->key<<' ';
               inorder_tree_walk(x->right);
         }
    }

    查找

    递归:

    Nod * tree_search(Nod *x,int k)
    {
             if(x==NULL||k==x->key)return x;
             if(k<x->key)
                    return tree_search(x->left,k);
             else
                    return tree_search(x->right,k);
    
    }

    迭代:

    Nod * tree_search(Nod *x,int k)
    {
              while(x!=NULL&&x->key!=k){
                     if(k<x->key){
                         x=x->left;
                     }else{
                        x=x->right;
                     }
              }
              return x;
    
    }

    最小关键字

    Nod * tree_min(Nod* x)
    {
              while(x->left!=NULL){
                  x=x->left;
              }
              return x;
    }

    最大关键字

    Nod * tree_max(Nod* x)
    {
              while(x->right!=NULL){
                  x=x->right;
              }
              return x;
    }

    后继

    Nod * tree_successor(x)
    {
              if(x->right!=NULL)
                      return tree_min(x->right);
              y=x->p;
              while(y!=NULL&&x==y->right){
                       x=y;
                       y=y->p;
              }
              return y;
    }

    前驱

    Nod * tree_predecessor(x)
    {
              if(x->left!=NULL)
                      return tree_max(x->left);
              y=x->p;
              return y;
    }

    插入

    void tree_insert(Nod*root,Nod *x)
    {
             Nod* x,y;
             y=NULL;
             x=root;
             while(x!=NULL){
                  y=x;
                  if(z->key<x->key){
                         x=x->left;
                  }
                  else x=x->right;
              }
              z->p=y;
              if(y==NULL);
              else if(z->key<y->key)y->left=z;
              else y->right=z;
    }

    删除

  • 相关阅读:
    1144 The Missing Number (20分)
    1145 Hashing
    1146 Topological Order (25分)
    1147 Heaps (30分)
    1148 Werewolf
    1149 Dangerous Goods Packaging (25分)
    TypeReference
    Supervisor安装与配置()二
    谷粒商城ES调用(十九)
    Found interface org.elasticsearch.common.bytes.BytesReference, but class was expected
  • 原文地址:https://www.cnblogs.com/liulex/p/11237004.html
Copyright © 2011-2022 走看看