109. 有序链表转换二叉搜索树

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:   

      0
     / 
   -3   9
   /   /
 -10  5

此题目是将一个按照升序排序的单链表转化为二叉搜索树,只需要找到二叉树的根节点即可,左右子树均可用递归的方法来生成。

根节点就是链表的中位数,也就是所给链表的中间的那一个数。找有序链表中间的那一个数可以用slow 和fast指针来进行,初始化

slow=null fast=head 每次slow指针前进一步,fast指针前进两部,直到fast.next==null&&fast.next.next==null为止,此时slow指针指

向中间那个数的前一个数,这样就可以找到中间的数。代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode() {}
 7  *     ListNode(int val) { this.val = val; }
 8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 9  * }
10  */
11 /**
12  * Definition for a binary tree node.
13  * public class TreeNode {
14  *     int val;
15  *     TreeNode left;
16  *     TreeNode right;
17  *     TreeNode() {}
18  *     TreeNode(int val) { this.val = val; }
19  *     TreeNode(int val, TreeNode left, TreeNode right) {
20  *         this.val = val;
21  *         this.left = left;
22  *         this.right = right;
23  *     }
24  * }
25  */
26 class Solution {
27     public TreeNode sortedListToBST(ListNode head) {
28         if(head==null)
29              return null;
30          if(head.next==null)
31              return new TreeNode(head.val);
32          ListNode slow=null,fast=head;
33          while(fast!=null&&fast.next!=null) {
34              fast=fast.next.next;
35              if(slow==null)
36                  slow=head;
37              else
38                  slow=slow.next;
39          }
40          TreeNode root=new TreeNode(slow.next.val);
41          ListNode right=slow.next.next;
42          slow.next=null;
43          root.left=sortedListToBST(head);
44          if(right==null)
45              root.right=null;
46          else
47              root.right=sortedListToBST(right);
48          return root;
49     }
50 }
原文地址:https://www.cnblogs.com/kaiwei123/p/13521198.html