【Leetcode】Convert Sorted List to Binary Search Tree
来源:互联网 发布:淘宝详情模板代码 编辑:程序博客网 时间:2024/04/30 08:51
【题目】Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
【思路】这道题目就和array不一样,因为是linkedlist所以,不能随意访问到中间的元素,那么就只能一步一步从头开始顺序访问,从列表到BST,我们能感受到构造的规律,所以这次通过定出list, bottom-up来构造起树。
间接了大神的分析:
constructing the tree from leaves to root,to do that insert nodes in BST in the same order as the appear in Linked List, by doing so the time complexity would be simply O(n) as we just need to traverse the linked list.
STEP 1: Take left n/2 nodes and recursively construct the left sub tree.
STEP 2: After left sub tree is constructed, we allocate memory for root and link the left sub tree with root.
STEP 3: Finally, we recursively construct the right sub tree and link it with root.
NOTE :: While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call.
这也算是inorder traversal了吧!
【代码】
public class Solution { private ListNode cur; public TreeNode sortedListToBST(ListNode head) { cur = head; return generate(count(head)); } private TreeNode generate(int n){ if (0 == n) return null; TreeNode node = new TreeNode(0); node.left = generate(n/2); node.val = cur.val; cur = cur.next; node.right = generate(n-n/2-1); return node; } private int count(ListNode h){ int size = 0; while (h != null){ ++size; h = h.next; } return size; }}
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- LeetCode[Tree]: Convert Sorted List to Binary Search Tree
- [leetcode][list][dfs] Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- LeetCode : Convert Sorted List to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Balanced Binary Search Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- leetcode 66: Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- [Leetcode]Convert Sorted List to Binary Search Tree
- [leetcode]Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Binary Search Tree
- UIImageview点击事件
- 于LINUX的开放式结构数控系统组成及特点
- 由12306.cn谈谈网站性能技术
- CryptoJS v3.1.2实现md5数据加密实例
- tomcat服务器配置
- 【Leetcode】Convert Sorted List to Binary Search Tree
- Mysql数据库的使用总结之ERROR 1146 (42S02)
- android之单选框
- 搭建Maven私服
- Java 技术能做什么
- Nginx+FastCGI+PHP-2
- SharedPreferences 数据共享问题
- Android中的事件处理研究
- Qt Quick实现的涂鸦程序