LeetCode#109. Convert Sorted List to Binary Search Tree
来源:互联网 发布:网络集成商 编辑:程序博客网 时间:2024/06/04 22:59
题目:将一个排序后链表转成一个平衡二叉查找树
难度:Medium
思路:这题的思路跟将有序数组转成平衡二叉查找树一样,查找一个链表的中间元素需要定义两个指针,fast指针每次移动两步,slow指针每次移动一步,fast指针移动到链表尾部时,slow指向的节点为中间节点
- 代码:
public class Solution { public TreeNode sortedListToBST(ListNode head) { if(head == null){ return null; } return recursion(head, null); } public TreeNode recursion(ListNode head, ListNode tail){ if(head == tail){ return null; } ListNode slow = head; ListNode fast = head; while(fast != tail && fast.next != tail){ slow = slow.next; fast = fast.next.next; } TreeNode node = new TreeNode(slow.val); node.left = recursion(head, slow); node.right = recursion(slow.next, tail); return node; }}
阅读全文
0 0
- 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 Python
- [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
- 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
- Leetcode-109. Convert Sorted List to Binary Search Tree
- 【leetcode】109. Convert Sorted List to Binary Search Tree
- 解决 github push failed (remote: Permission to userA/repo.git denied to userB.)
- 1115. Counting Nodes in a BST (30)
- Discuz X3.2 论坛关闭后,MySQL帖子导出为.csv
- 机器学习之数学基础(概率与统计推断、矩阵、凸优化)
- 步步紧逼!英特尔至强E7 v3对决IBM POWER8
- LeetCode#109. Convert Sorted List to Binary Search Tree
- Zookeeper集群搭建(涵盖命令详解)与Error contacting service. It is probably not running的问题解决
- Android匿名共享内存和MemoryFile
- C语言:列举system函数如何修改控制台背景及文字颜色
- hdu 4348 主席树的区间更新
- eclipse如何修改dynamic web module version
- iOS分享授权问题:-canOpenURL: failed ..."This app is not allowed to query for sscheme xx
- linux 下应用编程进程内存资源的限制
- Socket 编程