Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.
Example
Given [1,2,3,4,5,6,7] , return
4 / 2 6 / \ / 1 3 5 7
Note
There may exist multiple valid solutions and return any of them.
Thinking more direct, the middle number as root, the first half as the left subtree, the latter half as the right sub-tree
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramA:an Integer Array *@return: A tree node*/ PublicTreeNode Sortedarraytobst (int[] A) {//Write your code here if(A = =NULL|| A.length = = 0) return NULL; TreeNode Root= Gettree (A, 0, A.length-1); returnRoot; } PublicTreeNode Gettree (int[] A,intStartintend) { if(Start >end)return NULL; intMID = start + (End-start)/2; TreeNode Root=NewTreeNode (A[mid]); TreeNode Left= Gettree (A, start, mid-1); TreeNode Right= Gettree (A, Mid + 1, end); Root.left=Left ; Root.right=Right ; returnRoot; } }
Lintcode-easy-convert Sorted Array to Binary Search Tree with Minimal Height