share my C# code with fast and slow runner


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode SortedListToBST(ListNode head) {
            return buildHelper(head);
        }
        //unit test null, [1],[1,2]
        public TreeNode buildHelper(ListNode head)
        {
            if(head==null)
                return null;
            //find mid
            ListNode fast=head.next;
            ListNode slow=head;
            ListNode pre=null;
            while(fast != null && fast.next != null)
            {
                fast = fast.next.next;
                pre = slow;
                slow = slow.next;
            }
            if(pre!=null)
                pre.next=null;
            //cut list
            TreeNode root = new TreeNode(slow.val);
            if(slow!=head)
                root.left = buildHelper(head);
            root.right = buildHelper(slow.next);
            return root;
        }
    }

Log in to reply
 

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