/** * 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) { if(head == null){ return null; } var nodes = new List(); while(head != null){ nodes.Add(head.val); head = head.next; } TreeNode root = null; BuildTree(nodes,ref root); return root; } private void BuildTree(IList values,ref TreeNode n){ if(values.Count == 0){ return; } var mid = (int)(values.Count/2); var self = values[mid]; n = new TreeNode(self); var leftVals= values.Where(x=>x < self); var rightVals = values.Where(x=>x > self); if(leftVals.Any()){ BuildTree(leftVals.ToList() ,ref n.left); } if(rightVals.Any()){ BuildTree(rightVals.ToList(),ref n.right); } } }