【leetcode刷题笔记】Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题解:开始想到的方法比较偷懒,直接遍历一遍数组,把每个ListNode对应的值放到数组里面,然后把数组转换成BST,想来这个题的本意肯定不是这样。
自己也想到了bottom-up的方法,但是没想明白怎么个bottom-up法,真的是昨天做梦都在想=。=
今天早上终于弄懂了,用递归,不过这个递归比较难理解。
递归函数的定义是这样的 public TreeNode sortLisTreeNodeRecur(int size) ,参数size的意义可以理解为要建立的树的节点个数。用一个current变量作为linked list的游标。递归函数的实现如下:
1 public TreeNode sortLisTreeNodeRecur(int size){ 2 if(size <= 0) 3 return null; 4 5 TreeNode left = sortLisTreeNodeRecur(size/2); 6 TreeNode root = new TreeNode(current.val); 7 current = current.next; 8 TreeNode right = sortLisTreeNodeRecur(size - size/2 - 1); 9 10 root.left = left; 11 root.right = right; 12 13 return root; 14 }
可以看到,它先递归调用自己建立整个左子树,在这个过程中,current作为全局私有变量,在左子树建立完成以后,就自动移动到根节点对应的ListNode处了,所以建立完左子树后建立根节点,后移current,然后递归的建立整个右子树。
以Linked List = 1->2->3->4->5来画图说明:
代码如下:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; next = null; } 7 * } 8 */ 9 /** 10 * Definition for binary tree 11 * public class TreeNode { 12 * int val; 13 * TreeNode left; 14 * TreeNode right; 15 * TreeNode(int x) { val = x; } 16 * } 17 */ 18 public class Solution { 19 private ListNode current; 20 public int getLength(ListNode head){ 21 int answer = 0; 22 while(head != null){ 23 answer++; 24 head = head.next; 25 } 26 27 return answer; 28 } 29 public TreeNode sortLisTreeNodeRecur(int size){ 30 if(size <= 0) 31 return null; 32 33 TreeNode left = sortLisTreeNodeRecur(size/2); 34 TreeNode root = new TreeNode(current.val); 35 current = current.next; 36 TreeNode right = sortLisTreeNodeRecur(size - size/2 - 1); 37 38 root.left = left; 39 root.right = right; 40 41 return root; 42 } 43 public TreeNode sortedListToBST(ListNode head) { 44 current = head; 45 int size = getLength(head); 46 return sortLisTreeNodeRecur(size); 47 } 48 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了