109. Convert Sorted List to Binary Search Tree.java - \/My brute force way to solve this question public class Solution cfw public TreeNode

# 109. Convert Sorted List to Binary Search Tree.java - /My...

This preview shows page 1 - 2 out of 2 pages.

//My brute force way to solve this question public class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; if (head.next == null) return new TreeNode(head.val); ListNode fast = head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; pre = pre.next; } ListNode slow = pre.next; pre.next = null; TreeNode root = new TreeNode(slow.val); if (head == slow) root.left = null; else root.left = sortedListToBST(head); root.right = sortedListToBST(slow.next); return root; } } //O(n) solution public class Solution {

#### You've reached the end of your free preview.

• Spring '18
• Left-wing politics, public class Solution

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern