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 Solution {
	public TreeNode sortedArrayToBST(int[] num) {
		if (num == null) return null;
		return arrayToBST(num, 0, num.length - 1);
	}

	private TreeNode arrayToBST(int[] num, int l, int r) {
		if (l > r) return null;
		int m = (l + r) / 2;
		TreeNode cur = new TreeNode(num[m]);
		cur.left = arrayToBST(num, l, m - 1);
		cur.right = arrayToBST(num, m + 1, r);
		return cur;
	}
}

IDEA: 

Use data, in the range (l, r), to construct the current tree. First pick the middle element as the value of root. Then recursively construct the left sub-tree using data (i, m-1), and the right sub-tree(m+1, r). The initial condition is (1) i > j, the sub-tree being constructed is null, or (2) the sub-tree being constructed is a leaf (already included in case 1).


發佈了24 篇原創文章 · 獲贊 0 · 訪問量 4863
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章