码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA向,二叉查找树

时间:2014-05-24 08:04:52      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   java   

满足二叉查找树的存储规则。

类似折半查找:

bubuko.com,布布扣
import javax.management.remote.rmi._RMIConnectionImpl_Tie;

/**
 * Created by John on 14-5-22.
 */
public class IntTree {
    private static class IntTreeNode
    {
        private int data;
        private IntTreeNode leftLink;
        private IntTreeNode rightLink;

        public IntTreeNode(int newData,IntTreeNode newLeftLink,IntTreeNode newRightLink)
        {
            data =newData;
            leftLink=newLeftLink;
            rightLink=newRightLink;
        }
    }
    private IntTreeNode root;
    public IntTree()
    {
        root=null;
    }
    public void add(int item)
    {
        root=insertInSubtree(item,root);
    }
    public boolean contains(int item)
    {
        return isInSubtree(item,root);
    }
    public void showElements()
    {
        showElementsInSubtree(root);
    }
    private static boolean isInSubtree(int item,IntTreeNode subTreeRoot)
    {
        if(subTreeRoot==null)
            return new IntTreeNode(item,null,null);
        else if(item <subTreeRoot.data)
        {
            subTreeRoot.leftLink=insertInSubtree(item, subTreeRoot.leftLink);
            return subTreeRoot;
        }
        else
        {
            subTreeRoot.rightLink=insertInSubtree(item,subTreeRoot.rightLink);
            return subTreeRoot;
        }
    } 
    private static boolean isInSubtree(int item,IntTreeNode subTreeRoot)
    {
        if(subTreeRoot==null)
            return false;
        else if(subTreeRoot.data==item)
            return true;
        else if(item<subTreeRoot.data)
            return isInSubtree(item,subTreeRoot.leftLink);
        else
            return isInSubtree(item,subTreeRoot.rightLink);
    }
    private static void showElementsInSubtree(IntTreeNode subTreeRoot)
    {
        if(subTreeRoot!=null)
        {
            showElementsInSubtree(subTreeRoot.leftLink);
            System.out.print(subTreeRoot.data+" ");
            showElementsInSubtree(subTreeRoot.rightLink);
        }
    }
}
bubuko.com,布布扣

 

JAVA向,二叉查找树,布布扣,bubuko.com

JAVA向,二叉查找树

标签:style   class   blog   c   code   java   

原文地址:http://www.cnblogs.com/pengjunwei/p/3746709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!