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

    删除

  • 相关阅读:
    [转]Modernizr的介绍和使用
    java动态代理使用详解
    ajax上传文件以及使用中常见问题处理
    cmd下查询端口占用以及根据进程id名称结束进程
    水平居中 垂直居中
    inline-block和float
    一起入门前端(三)
    一起入门前端(二)
    一起入门前端(一)
    WPF初学——自定义样式
  • 原文地址:https://www.cnblogs.com/liulex/p/11237004.html
Copyright © 2011-2022 走看看