LeetCode 109 Convert Sorted List to Binary Search Tree
来源:互联网 发布:d3.js官网是什么 编辑:程序博客网 时间:2024/05/21 19:47
题目描述
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析
参考:LeetCode 108 Convert Sorted Array to Binary Search Tree
但是不能将linked list转换成arraylist,会超时。思路:快慢指针。
代码
ListNode cutAtMid(ListNode head) { if (head == null) { return null; } ListNode fast = head; ListNode slow = head; ListNode pslow = head; while (fast != null && fast.next != null) { pslow = slow; slow = slow.next; fast = fast.next.next; } pslow.next = null; return slow; } public TreeNode sortedListToBST(ListNode head) { if (head == null) { return null; } if (head.next == null) { return new TreeNode(head.val); } ListNode mid = cutAtMid(head); TreeNode root = new TreeNode(mid.val); root.left = sortedListToBST(head); root.right = sortedListToBST(mid.next); return root; }
0 0
- LeetCode(109)Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree [109]
- LeetCode 109 Convert Sorted List to Binary Search Tree
- LeetCode 109 Convert Sorted List to Binary Search Tree
- [leetcode 109] Convert Sorted List to Binary Search Tree
- [LeetCode 109]Convert Sorted List to Binary Search Tree
- leetcode || 109、Convert Sorted List to Binary Search Tree
- 【leetcode】【单链表】【109】Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree - LeetCode 109
- leetcode[109]:Convert Sorted List to Binary Search Tree
- LeetCode(109) Convert Sorted List to Binary Search Tree
- Leetcode #109 Convert Sorted List to Binary Search Tree
- leetcode 109: Convert Sorted List to Binary Search Tree
- LeetCode(109) Convert Sorted List to Binary Search Tree
- 109 Convert Sorted List to Binary Search Tree [Leetcode]
- LeetCode—109 Convert Sorted List to Binary Search Tree
- 【LEETCODE】109-Convert Sorted List to Binary Search Tree
- LeetCode 109 Convert Sorted List to Binary Search Tree
- Howto Enable and Use A2DP Sink on Ubuntu Linux with Bluez
- nyoj 20
- Java入门常识
- iOS9不能正常使用HTTP的解决方法
- 数据库_MYSQL获取自增主键【4种方法】 ,推荐方法3
- LeetCode 109 Convert Sorted List to Binary Search Tree
- 在linux下用tomcat部署java web项目的过程与注意事项__转载借用
- UNIX网络编程——读写锁
- Unable to load native-hadoop library for your platform
- UE4 Lens Flare
- SQL事务处理 C#
- ros错误集锦
- 《apue》环境搭建---apue.h
- VC: Nafxcwd.lib(dllmodul.obj) : error LNK2005: _DllMain@12 已经在dllmain.obj 中定义