生成高度最小的二叉查找树--CreatMinimalBST

本文介绍了一种从有序整数数组构建高度最小的二叉查找树的方法,并提供了详细的Java实现代码。通过递归地选择中间元素作为根节点,确保了树的高度尽可能小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

给定一个有序整数数组,元素隔壁相同且按升序排列,编写一个算法,创建一棵高度最小的二叉查找树

代码

public class CreatMinimalBST {

	/**
	 * 
	 */
	public static TreeNode creatMinimalBST(int arr[]) {
		if (arr == null || arr.length == 0) {
			return null;
		}
		int start = 0;
		int end = arr.length - 1;
		TreeNode node = doCreatMinimalBST(arr, start, end);
		return node;
	}

	public static TreeNode doCreatMinimalBST(int arr[], int start, int end) {
		if (end < start) {
			return null;
		}
		int mid = (start + end) / 2;
		TreeNode node = new TreeNode(arr[mid]);
		node.left = doCreatMinimalBST(arr, start, mid - 1);
		node.right = doCreatMinimalBST(arr, mid + 1, end);

		return node;
	}

	public static void printTree(TreeNode root) {
		System.out.println(root.value);//先序打印
		if (root.left != null) {
			printTree(root.left);
		}
		// System.out.println(root.value);//中序打印
		if (root.right != null) {
			printTree(root.right);
		}
		// System.out.println(root.value);//后序打印
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int test[] = { 1, 2, 3, 4, 5 };
		TreeNode node = creatMinimalBST(test);
		// 生成树
		//   3
		//  / \
		// 1   4
		//  \   \
		//   2   5
		printTree(node);
	}

}

输出

3
1
2
4
5


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值