java 109.将Sorted List转换为二进制搜索Tree.java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 109.将Sorted List转换为二进制搜索Tree.java相关的知识,希望对你有一定的参考价值。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
return helper(head,null);
}
public TreeNode helper(ListNode head, ListNode tail){
ListNode fast = head;
ListNode slow = head;
if(head == tail) return null;
//while(fast != tail && fast.next != tail){
//[1,2,3,4,5][1,2,3,4]
//[3,2,5,1,null,4][3,2,4,1]
while(fast.next != tail && fast.next.next != tail){
//[1,2,3,4,5][1,2,3,4]
//[3,1,4,null,2,null,5][2,1,3,null,null,null,4]
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = helper(head, slow);
root.right = helper(slow.next, tail);
return root;
}
}
以上是关于java 109.将Sorted List转换为二进制搜索Tree.java的主要内容,如果未能解决你的问题,请参考以下文章
java 109.将Sorted List转换为二进制搜索Tree.java
java 109.将Sorted List转换为二进制搜索Tree.java
java 109.将Sorted List转换为二进制搜索Tree.java
java 109.将Sorted List转换为二进制搜索Tree.java
[LeetCode] 109. Convert Sorted List to Binary Search Tree
LeetCode-面试算法经典-Java实现109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)