1. 程式人生 > >二叉搜尋樹中求得給定元素的下界

二叉搜尋樹中求得給定元素的下界

public static BianrySearchTreeNode FloorInBST(BianrySearchTreeNode root,int data){
		if(root==null)
			return null;
		if(root.getData()==data)
			return root;
		if(data<root.getData()){     //查詢值小於當前節點的值
			if(data<FindMin(root).getData())//小於整個樹的最小值
				return null;
			if(data>=FindMax(root.getLeft()).getData())
				return FindMax(root.getLeft());
			else
				return FloorInBST(root.getLeft(),data);
		}
		if(root.getData()<data){    //查詢值大於當前節點的值
			if(data>=FindMax(root.getRight()).getData())// 大於整棵樹的最大值
				return FindMax(root);
			if(data<FindMin(root.getRight()).getData())//小於右子樹的最小值
				return root;
			else
				return FloorInBST(root.getRight(),data);
		}
		return null;
	}

順便記錄一下FindMax與FindMin的函式如下:

        //搜尋最小元素
	public static BianrySearchTreeNode FindMin(BianrySearchTreeNode root){
		if(root==null)
			return null;
		while(root.getLeft()!=null)
			root = root.getLeft();
		return root;
	}
	
	//搜尋最大元素
	public static BianrySearchTreeNode FindMax(BianrySearchTreeNode root){
		if(root==null)
			return null;
		while(root.getRight()!=null)
			root = root.getRight();
		return root;
	}