`
473687880
  • 浏览: 482441 次
文章分类
社区版块
存档分类
最新评论

Convert Sorted Array to Binary Search Tree @LeetCode

 
阅读更多
package Level2;

import Utility.TreeNode;

/**
 * Convert Sorted Array to Binary Search Tree  
 * 
 * Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
 */
public class S108 {

	public static void main(String[] args) {
		int[] num = {1,3};
		TreeNode n = sortedArrayToBST(num);
		n.print();
	}
	
	public static TreeNode sortedArrayToBST(int[] num) {
		return sortedArrayToBSTRec(num, 0, num.length-1);
    }
	
	// 二分查找节点值,并递归创建节点
	private static TreeNode sortedArrayToBSTRec(int[] num, int low, int high){
		if(low > high){
			return null;
		}
		int mid = low + (high-low)/2;		// 找到中值
		TreeNode root = new TreeNode(num[mid]);		// 创建根节点
        root.left = sortedArrayToBSTRec(num, low, mid-1);		// 递归创建左子树和右子树
        root.right = sortedArrayToBSTRec(num, mid+1, high);
		return root;
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics