Easy to understand Java Solution 1 ms


  • 0
    E
    /**
     * 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) {
            ListNode tmp=new ListNode(0);
            tmp.next=head;
            return TreeHelper(tmp);
        }
        public TreeNode TreeHelper(ListNode head){
            if (head.next == null) {
    			return null;
    		}
    		ListNode slow = head, fast = head, prev = slow, l1 = head;
    		while (fast != null && fast.next != null) {
    			prev = slow;
    			slow = slow.next;
    			fast = fast.next.next;
    		}
    		ListNode l2 = slow;
    		prev.next = null;
    		TreeNode root = new TreeNode(slow.val);
    		root.left = TreeHelper(l1);
    		root.right = TreeHelper(l2);
    		return root;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.