首页 > 其他 > 详细

二叉搜索树

时间:2016-02-26 00:33:53      阅读:215      评论:0      收藏:0      [点我收藏+]

二叉搜索树是以一颗二叉树来组织的。这棵树可以使用链表数据结构表示。每个节点除了key和卫星数据外。每个节点包含属性left、right、parent。二叉搜索树中树,如果x是一个节点,则x.left.key < x.key < x.right.key。

中序遍历、前序遍历、后续遍历

InorderTreeWalk(x)
{
    if(x != null)
    {
        InorderTreeWalk(x.left);
        print x.key;
        InorderTreeWalk(x.right);
    }
}
PreorderTreeWalk(x)
{
    if(x != null)
    {
        print x.key;
        InorderTreeWalk(x.left);
        InorderTreeWalk(x.right);
    }
}
PostorderTreeWalk(x)
{
    if(x != null)
    {
        InorderTreeWalk(x.left);
        InorderTreeWalk(x.right);
        print x.key;
    }
}

查询-递归

TreeSearch(x, k)
{
    if(x == null || k == x.key)
        return x;
    if(k < x.key)
        return TreeSearch(x.left, k);
    return TreeSearch(x.right, k);
}

查询-循环

TreeSearch(x, k)
{
    while(x != null && k != x.key)
    {
        if(k < x.key)
            x = x.left;
        else
            x = x.right;
    }
     return x;
}

最大

TreeMaximum(x)
{
    while(x != null)
    {
            x = x.right;
    }
     return x;
}

最小

TreeMinimum(x)
{
    while(x != null)
    {
            x = x.left;
    }
     return x;
}

后继和前驱

右子树不空,则x后继为右子树最小节点。右子树为空,那x后继就是其最底层祖先。总的来说就是,后继就是x大的最小的数。

TreeSuccessor(x)
{
  if(x.right != null)
    return TreeMinimum(x.right);
  y=x.parent;
  while(y != null && x==y.right)
  {
    x=y;
    y=y.parent
  }
  return y;
}

插入

TreeInsert(T, z)
{
  y=null;
  x=T.root;
  while(x != null)
  {
    y=x;
    if(z.key < x.key)
      x=x.left;
    else
      x=x.right;
} x.parent
=y; if(y == null) T.root=z; else if(z.key < y.key) y.left=z; else y.right=z; } }

删除z

  1. 如果z没有孩子,删除之z=null
  2. 如果z只有一个孩子,z.child<l or r>.p=p.p; z.p.child<l or r>=z.child<l or r>.p
  3. 如果有两个孩子,则z的后继y需要占领z,然后在考虑将z的子树与y的子树合并问题
Transplant(T, u, v)
{
    if (u.parent == null)
        t.root = v
    else if (u == u.parent.left)
        u.p.left = v;
    else
        u.p.right = v;
    if (v != null)
        v.parent = u.partent;
}
TreeDelete(T, z)
{
    if (z.left == null)
        Transplant(T, z, z.right);
    else if (z.right == null)
        Transplant(T, z, z.left);
    else
    {
        y = TreeMinimum(z.right);//z有双子,则后继为右侧最小
        if (y.parent != z)
        {
            Transplant(T, y, y.right);
            y.right = z.right;
            y.right.parent = y;
        }
        Transplant(T, z, y);
        y.left = z.left;
        y.left.parent = y;
    }
}

 

二叉搜索树

原文:http://www.cnblogs.com/qiusuo/p/5218777.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!