109. Convert Sorted List to Binary Search Tree
不定期更新leetcode解题java答案。
采用pick one的方式选择题目。
题意为将一个增序单链表转换成为二叉搜索树。
可以采用递归的方式依次确认该层应选择的单链表位置作为树的节点依次向下进行。每次选择做树该层的节点为链表的中间值。
代码如下:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 /** 10 * Definition for a binary tree node. 11 * 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 public TreeNode sortedListToBST(ListNode head) { 20 return sortedListToBST(head, null); 21 } 22 23 public TreeNode sortedListToBST(ListNode head, ListNode tail){ 24 if(head == tail) 25 return null; 26 ListNode slow = head, fast = head; 27 28 while(fast != tail && fast.next != tail){ 29 slow = slow.next; 30 fast = fast.next.next; 31 } 32 TreeNode root = new TreeNode(slow.val); 33 34 root.left = sortedListToBST(head, slow); 35 root.right = sortedListToBST(slow.next, tail); 36 37 return root; 38 } 39 }
此外,仍列出读取单链表后生成二叉搜索树的方法,代码如下:
1 public class Solution { 2 public TreeNode sortedListToBST(ListNode head) { 3 ArrayList<Integer> list = new ArrayList(); 4 while(head != null){ 5 list.add(head.val); 6 head = head.next; 7 } 8 9 TreeNode tn = null; 10 if(list.size() != 0){ 11 12 int size = list.size() - 1; 13 tn = new TreeNode(list.get(size / 2)); 14 15 getLeftNode(tn, list, 0, size / 2 - 1); 16 getRightNode(tn, list, size / 2 + 1, size); 17 } 18 return tn; 19 } 20 21 public void getLeftNode(TreeNode node, ArrayList<Integer> list, int start, int end){ 22 if(start > end) 23 return; 24 int mid = (start + end) / 2; 25 node.left = new TreeNode(list.get(mid)); 26 27 getLeftNode(node.left, list, start, mid - 1); 28 getRightNode(node.left, list, mid + 1, end); 29 } 30 31 public void getRightNode(TreeNode node, ArrayList<Integer> list, int start, int end){ 32 if(start > end) 33 return; 34 int mid = (start + end) / 2; 35 node.right = new TreeNode(list.get(mid)); 36 37 getLeftNode(node.right, list, start, mid - 1); 38 getRightNode(node.right, list, mid + 1, end); 39 } 40 }