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

0
/ \
-3   9
/   /
-10  5

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
}

public TreeNode buildTree(ListNode left,ListNode right){
if(left==right){
return null;
}
ListNode mid = getMid(left,right);
TreeNode root = new TreeNode(mid.val);
root.left = buildTree(left,mid);
root.right = buildTree(mid.next,right);
return root;
}

public ListNode getMid(ListNode left,ListNode right){
ListNode slow = left;
ListNode fast = left;
while(fast != right && fast.next != right){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

欢脱的婷子

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
02-02 106

06-02 473
08-12 45
05-18 186
04-18 181
10-12 1429