二叉查找树的一些操作(search,getminvalue,get maxvalue,insert)

在前一篇关于二叉查找树中,我们创建了一个二叉查找树,然后用递归和非递归的方法,遍历了树中的所有节点,文章的地址:http://www.cnblogs.com/chenping-987123/archive/2010/09/25/1834341.html

下面我们就进一步多了解一下关于这个二叉查找树其他的功能:

(1) search功能:在二叉查找树中查找某个节点,代码如下:(根据二叉查找树的性质左节点的value<=根节点的value<=右节点的value)

 private static MyNode TreeSearch(MyNode root, int p)
        {
            if (root == null || root._value == p)
            {
                return root;
            }
            if (p < root._value)
            {
                return TreeSearch(root.left,p);
            }
            else
            {
                return TreeSearch(root.right, p);
            }
        }

(2) getminvalue(得到树中的最小值,根据性质,可以知道,二叉查找树的最小值就是最左边的节点),代码如下:

  private static MyNode TreeMin(MyNode root)
        {
            MyNode node = null;
            while (root != null)
            {
                node = root;
                root = root.left;
            }
            return node;
        }
(3) getmaxvalue(得到树中的最大值,根据性质,可以知道,二叉查找树的最大值就是最右边的节点),代码如下:
  private static MyNode TreeMax(MyNode root)
        {
            MyNode node = null;
            while (root != null)
            {
                node = root;
                root = root.right;
            }
            return node;
        }

(4) insert节点

 private static void InsertTreeNode(MyNode root, int p)
        {
            MyNode y = null;
            MyNode x = root;
            while (x != null)
            {
                y = x;
                if (p < x._value)
                {
                    x = x.left;
                }
                else
                {
                    x = x.right;
                }
            }
            MyNode z = new MyNode();
            z._value = p;
            z.parent = y;
            z.left = z.right = null;
            if (y ==null)
            {
                root = z;
            }
            else if (z._value < y._value)
            {
                y.left = z;
            }
            else
            {
                y.right = z;
            }
        }

posted @ 2010-09-26 17:03  chenping2008  阅读(764)  评论(0编辑  收藏  举报