Convert Sorted List to Binary Search Tree
来源:互联网 发布:office for mac 破解 编辑:程序博客网 时间:2024/05/17 08:36
原题是这个样子:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Thoughts
If you are given an array, the problem is quite straightforward. But things get a little more complicated when you have a singly linked list instead of an array. Now you no longer have random access to an element in O(1) time. Therefore, you need to create nodes bottom-up, and assign them to its parents. The bottom-up approach enables us to access the list in its order at the same time as creating nodes.
参考:http://www.programcreek.com/2013/01/leetcode-convert-sorted-list-to-binary-search-tree-java/代码如下:
public TreeNode sortedListToBST(ListNode head) {if (head == null)return null;int len = 0;ListNode nextNode = head;while (nextNode != null) {nextNode = nextNode.next;len++;}return buildTree(head, 0, len - 1);}public TreeNode buildTree(ListNode head, int start, int end) {if (start > end)return null;int mid = (start + end) / 2;ListNode p = head;for (int i = start; i < mid; i++) {p = p.next;}TreeNode left = buildTree(head, start, mid - 1);TreeNode right = buildTree(p.next, mid + 1, end);TreeNode root = new TreeNode(p.val);root.left = left;root.right = right;return root;}
0 0
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- convert sorted list to binary search tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Python 内置函数sorted详解和itemgetter, attrgetter
- 获取连接到本机AP热点设备的IP地址
- Android_基础知识_03_获取屏幕的高度和宽度
- java和C结构体通信
- 第16周项目2 单词的个数
- Convert Sorted List to Binary Search Tree
- 机器学习经典算法详解及Python实现--K近邻(KNN)算法
- Android 用Animation-list实现逐帧动画
- centos自动拨号上网
- 微信分享缩略图自定义
- 关于Java中的内存指向问题(Date)
- xcode设置支持32位
- SSD5 option 4
- Collection相关