Convert Sorted Array to Binary Search Tree
Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
A very simple dichotomy, as long as the start and end of the array is given as a parameter to pass the index.
1 PublicTreeNode Sortedarraytobst (int[] num) {2 returnConstructbst (num,0,num.length-1);3 }4 PublicTreeNode Constructbst (int[] num,intStartintend) {5 if(start>end)6 return NULL;7 if(start==end)8 return NewTreeNode (Num[start]);9 intMid = (start+end)/2;TenTreeNode root =NewTreeNode (Num[mid]); OneRoot.left = Constructbst (num, start, mid-1); ARoot.right = Constructbst (num, mid+1, end); - returnRoot; -}
Convert Sorted List to Binary Search Tree
Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
For a linked list, the situation is slightly more complicated, and the simplest idea is that you can iterate through the linked list and save it in an array and build it. The direct construction method here is to use the fast pointer to find the midpoint of the list, the left half of the list ends point to null, and recursively constructs a left subtree. The right half of the part is built recursively into the right sub-tree. If you do not want to destroy the original linked list, then you can use the first to save to the array and then build the method.
1 PublicTreeNode Sortedlisttobst (ListNode head) {2 if(head==NULL)3 return NULL;4 if(Head.next = =NULL)5 return NewTreeNode (head.val);6ListNode fast =Head.next;7ListNode slow =head;8 while(fast!=NULL&& fast.next!=NULL&& fast.next.next!=NULL) {9Fast =Fast.next.next;Tenslow =Slow.next; One } AListNode root =Slow.next; -Slow.next =NULL; -TreeNode Troot =NewTreeNode (root.val); theTroot.left =Sortedlisttobst (head); -Troot.right =Sortedlisttobst (root.next); - returnTroot; -}
[Leetcode] [JAVA] Convert Sorted Array to binary search tree && Convert Sorted List to binary search tree