109. Convert Sorted List to Binary Search Tree
来源:互联网 发布:九鼎彩社用的软件 编辑:程序博客网 时间:2024/06/09 23:54
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
这道题就是二分法,findmiddle,然后生成树的左边和右边,也findmiddle,同时要返回previous,将previous的next设置为null
class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) { return null; } ListNode[] node = findMiddle(head); ListNode prev = node[0]; ListNode mid = node[1]; TreeNode root = new TreeNode(mid.val); if (mid.next != null) { root.right = sortedListToBST(mid.next); } if (prev != null) { prev.next = null; } if (prev != null){ root.left = sortedListToBST(head); } return root; } private ListNode[] findMiddle(ListNode head) { ListNode[] res = new ListNode[2]; ListNode slow = head; ListNode fast = head.next; ListNode prev = null; while (fast != null && fast.next != null) { prev = slow; slow = slow.next; fast = fast.next.next; } res[0] = prev; res[1] = slow; return res; }}
阅读全文
0 0
- Tree-----109. 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
- js两只手指控制div图片放大缩小功能(2)
- Qt5.9.1+VS2015环境搭建
- 在浏览器地址栏键入URL之后经历的过程
- html添加swf文件,设置背景透明
- HEVC率失真优化
- 109. Convert Sorted List to Binary Search Tree
- Attention Is All You Need 论文阅读笔记
- 初识Node.js
- (M)Dynamic Programming: 413. Arithmetic Slices
- 伪类三角形
- 史上最全量化交易资源整理
- Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0
- mac OSX10.12 sierra 安装python-ldap报missing sasl.h错误
- 单例模式之懒汉的并发问题