Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Question: The method that comes to mind is relatively lazy. You can traverse the array directly, put the value of each listnode in the array, and then convert the array to BST, this is definitely not the case.
I also thought of the bottom-up method, but I didn't want to understand how to use the bottom-up method. I was dreaming about it yesterday. =
This morning I finally understood it and used recursion, but this recursion is hard to understand.
The recursive function is defined as public treenode sortlistreenoderecur (INT size). The meaning of the parameter size can be understood as the number of nodes in the tree to be created. Use a current variable as the cursor of the linked list. The implementation of recursive functions is as follows:
1 public TreeNode sortLisTreeNodeRecur(int size){ 2 if(size <= 0) 3 return null; 4 5 TreeNode left = sortLisTreeNodeRecur(size/2); 6 TreeNode root = new TreeNode(current.val); 7 current = current.next; 8 TreeNode right = sortLisTreeNodeRecur(size - size/2 - 1); 9 10 root.left = left;11 root.right = right;12 13 return root;14 }
As you can see, it recursively calls itself to build the entire left subtree. In this process, current is used as a global private variable. After the left subtree is created, the node is automatically moved to the listnode corresponding to the root node. Therefore, after the left subtree is created, the root node is established, the current node is moved back, and the entire right subtree is recursively created.
Use linked list = 1-> 2-> 3-> 4-> 5 to draw a picture:
The Code is as follows:
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 /**10 * Definition for binary tree11 * public class TreeNode {12 * int val;13 * TreeNode left;14 * TreeNode right;15 * TreeNode(int x) { val = x; }16 * }17 */18 public class Solution {19 private ListNode current;20 public int getLength(ListNode head){21 int answer = 0;22 while(head != null){23 answer++;24 head = head.next;25 }26 27 return answer;28 }29 public TreeNode sortLisTreeNodeRecur(int size){30 if(size <= 0)31 return null;32 33 TreeNode left = sortLisTreeNodeRecur(size/2);34 TreeNode root = new TreeNode(current.val);35 current = current.next;36 TreeNode right = sortLisTreeNodeRecur(size - size/2 - 1);37 38 root.left = left;39 root.right = right;40 41 return root;42 }43 public TreeNode sortedListToBST(ListNode head) {44 current = head;45 int size = getLength(head);46 return sortLisTreeNodeRecur(size);47 }48 }