recursion programming
1 public class Solution { 2 public TreeNode sortedListToBST(ListNode head) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 if(head == null) 6 return null; 7 ListNode tmp = head; 8 int count = 0; 9 while(tmp !=null){ 10 tmp = tmp.next; 11 count++; 12 } 13 return buildBST(head, count); 14 } 15 16 private TreeNode buildBST(ListNode head, int n) 17 { 18 if(head == null || n==0) 19 return null; 20 if(n == 1) 21 return new TreeNode(head.val); 22 int boundary = n/2; 23 ListNode tmp = head; 24 for(int i = 0; i < boundary; i++) 25 tmp = tmp.next; 26 TreeNode mynode = new TreeNode(tmp.val); 27 mynode.left = buildBST(head, boundary); 28 mynode.right = buildBST(tmp.next, n-boundary-1); 29 return mynode; 30 } 31 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步