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

    删除

  • 相关阅读:
    Rock the Tech Interview
    k-d Tree in TripAdvisor
    Randomized QuickSelect
    Kth Smallest Element in Unsorted Array
    Quick Sort
    LRU Cache 解答
    Implement Queue using Stacks 解答
    Implement Stack using Queues 解答
    ListNode Review ReverseListNode
    BackTracking
  • 原文地址:https://www.cnblogs.com/liulex/p/11237004.html
Copyright © 2011-2022 走看看