最小高度搜索树

最小高度搜索树

 分析:

  1. 注意要有叶子结点,也就是当没有分配的数的时候应该讲它的后继赋值为空
  2. 由于要先构造左子树和右子树,在将他链接到p根节点中,所以在这种情况下要求要有返回值的函数
  3. 单用带参数的方法貌似也可以直接构造树

题解为了便于查看题目多增加了,树的遍历,和数的层数最大求法。

/**
*@author yangyvting
*@date 2019年5月4日
*/
package 数结构;

public class 最小高度二叉搜索树 {
	public static int a[] = {1,2,3,4,5,6,7};
	public static int max = 0;

	public static void main(String[] args) {
		int nl = a.length;	 
		treeNode p = null ;
		//1.创建二叉搜索树
	    p = creatBinarySearchtree(0, nl - 1);
	    
	    //2.打印二叉搜索树
	    printBiSeaTree(p);
		 
        //3.输出最大高度
	    findMaxfloor(p, 0);
	    System.out.println();
	    System.out.println("最大高度为:");
	    System.out.println(max);
	}


	private static void findMaxfloor(treeNode p, int n) {
		//跳出递推
		if(p.left == null && p.right == null) {
			if(n > max) {
				max = n;
			}
			return;
		}
		
		//下一跳
		findMaxfloor(p.left, n + 1);
		findMaxfloor(p.right, n + 1);
		 
	}


	private static void printBiSeaTree(treeNode p) {
		//跳出递归
		if(p.left == null && p.right == null) {
			System.out.print (p.data + " ");
			return;
		}
		
		//下一跳
		if(p.left != null) {
			printBiSeaTree(p.left);
		}
		
		System.out.print (p.data + " ");
		
		if(p.right != null) {
			printBiSeaTree(p.right);
		}
		
		
	}


	private static treeNode creatBinarySearchtree(int i, int j) {
		//1.跳出递归
		if(i > j) {
			return null;
		}
		
		//2.构造树
		treeNode p = new treeNode( a[(i + j)/2]);
		treeNode le = creatBinarySearchtree(i,  (i + j)/2 - 1);
		treeNode ri = creatBinarySearchtree((i + j)/ 2 + 1, j);		
		p.left = le;
		p.right = ri;
		
		return p;
	}

}
class treeNode{
	int data;
	treeNode left;
	treeNode right;
	treeNode(int data){
		this.data = data;
	}
}

运行结果:

1 2 3 4 5 6 7 
最大高度为:
2