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.
I began to time out the problem, and then I thought of an opportunistic approach. To convert an array, and then use the method of the above question
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x; next = null;}7 * }8 */9 /**Ten * Definition for binary tree One * public class TreeNode { A * int val; - * TreeNode left; - * TreeNode right; the * TreeNode (int x) {val = x;} - * } - */ - Public classSolution { + PublicTreeNode Root; - Public intnums[]; + A PublicTreeNode Sortedlisttobst (ListNode head) { atListNode temp =head; - intLength = 0; - while(Temp! =NULL){ -Length + +; -temp =Temp.next; - } inNums =New int[length]; -temp =head; to for(inti = 0; i < nums.length; i++){ +Nums[i] =Temp.val; -temp =Temp.next; the } * returnSortedarraytobst (nums); $ }Panax Notoginseng - PublicTreeNode Sortedarraytobst (int[] num) { the if(Num.length = = 0) + returnRoot; A if(1 = =num.length) { the return NewTreeNode (num[0]); + } - intMiddle = NUM.LENGTH/2; $Root =NewTreeNode (Num[middle]); $ -Createbst (num, 0, middle-1); -Createbst (num, middle + 1, num.length-1); the returnRoot; - }Wuyi the /** - * Create a binary lookup tree based on the NUM array Wu * @paramNum - * @paramStart About * @paramEnd $ */ - Private voidCreatebst (intNum[],intStartintend) { - intMiddle = 0; - if(Start <= end && start >= 0 && End <num.length) { AMiddle = (start + end)/2; + the Insertnode (Root, Num[middle]); - $Createbst (num, start, middle-1); theCreatebst (num, middle + 1, end); the } the } the - /** in * Insert value into the BST two fork lookup tree referred to as root the * @paramRoot the * @paramvalue About */ the Private voidInsertnode (TreeNode root,intvalue) { the if(Value > Root.val) {//larger than the root node, inserted in the right sub-tree the if(Root.right = =NULL){ +Root.right =NewTreeNode (value); -}Else{ theRoot =Root.right;Bayi Insertnode (root, value); the } the } - Else{ - if(Root.left = =NULL){ theRoot.left =NewTreeNode (value); the}Else{ theRoot =Root.left; theInsertnode (root, value);//Insert the left subtree smaller than the root node - } the } the } the 94 /** the * First Order traversal the * @paramRoot the */98 Public voidpretravel (TreeNode root) { About if(Root! =NULL){ - //System.out.print (Root.val + "");101 Pretravel (root.left);102 Pretravel (root.right);103 }104 } the}
Convert Sorted List to Binary Search Tree