Tree_Graph 有序数组转BST @CareerCup

原文:

Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.

译文:

给定一个有序数组(递增),写程序构建一棵具有最小高度的二叉树。

思路:

因为是有序的数组,所以直接提取中数为root,然后递归建立其左子树和右子树


package Tree_Graph;

import CtCILibrary.TreeNode;

public class S4_3 {

	// 递归把有序数组转为BST
	public static TreeNode createMinBST(int[] A, 	int start, int end) {
		if ( start > end ) {
			return null;
		}
		
		int mid = (start + end) / 2;
		TreeNode root = new TreeNode(A[mid]);
		root.left = createMinBST(A, start, mid-1);
		root.right = createMinBST(A, mid+1, end);
		return root;
	}
	
	public static void main(String[] args) {
		int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

		// We needed this code for other files, so check out the code in the library
		TreeNode root = TreeNode.createMinimalBST(array);
		System.out.println("Root? " + root.data);
		System.out.println("Created BST? " + root.isBST());
		System.out.println("Height: " + root.height());
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值