Convert Sorted Array to Binary Search Tree
Problem:
Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
Ideas:
Recursive, DFS
My Code:
/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Sortedarraytobst (int[] num) { if(num = =NULL|| Num.length = = 0 ) return NULL ; intLen =num.length; TreeNode rst= Arraytobst (num, 0, len-1); returnrst; } PublicTreeNode Arraytobst (int[] num,intLeftintRight ) { if(Left > right)return NULL; if(left = right)return NewTreeNode (Num[left]); intMid = (left + right)/2; TreeNode Root=NewTreeNode (Num[mid]); Root.left= Arraytobst (num, left, mid-1); Root.right= Arraytobst (num, mid + 1, right); returnRoot; }}
View Code
Others code:
PublicTreeNode Sortedarraytobst (int[] num) { if(Num.length = = 0) { return NULL; } TreeNode head= Helper (num, 0, num.length-1); returnhead;} PublicTreeNode Helper (int[] num,intLowintHigh ) { if(Low > High) {// Done return NULL; } intMid = (low + high)/2; TreeNode node=NewTreeNode (Num[mid]); Node.left= Helper (num, Low, mid-1); Node.right= Helper (num, mid + 1, high); returnnode;}
View Code
The Learning Place:
- My code has redundancy where left = = Right judgment can be omitted
Convert Sorted Array to Binary Search Tree