Problem Description:
Converts an ordered array in ascending order to a highly balanced binary search tree.
In the subject, a highly balanced binary tree refers to the absolute value of the height difference of the left and right two subtrees of each node of a binary tree not exceeding 1.
Example:
Given an ordered array: [ -10,-3,0,5,9], one possible answer is: [0,-3,9,-10,null,5], which can represent the following highly balanced binary search tree: 0 / -3 9 / /-10 5
Problem Solving Ideas:
The array is divided into three parts with the most intermediate values of the array: the left half, the middle value, and the right half part;
Constructs the node with the middle value, the left half of the array constructs the left sub-tree of the node, right half right subtree;
Repeat for the left half of the array and the right part.
Implementation code:
Private StaticTreeNode Test (intNums[],intLointhi) { if(Lo > Hi)return NULL; if(lo = hi)return NewTreeNode (Nums[lo]); intMid = lo + (Hi-lo)/2; TreeNode node=NewTreeNode (Nums[mid]); Node.left= Test (Nums, lo, mid-1); Node.right= Test (Nums, mid+1, HI); returnnode; } Public StaticTreeNode Sortedarraytobst (intnums[]) { returnTest (nums, 0, Nums.length-1); }
Convert an ordered array to a two-fork search tree