[leetcode] 109. Convert Sorted List to Binary Search Tree
来源:互联网 发布:java获取list泛型类型 编辑:程序博客网 时间:2024/06/07 07:08
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
这道题是将已排序链表转化为高度平衡的二叉搜索树,题目难度为Medium。题目和108题(传送门)相关,感兴趣的同学可以先看下108题。
题目要求BST高度平衡,所以在转化链表某部分时要先找到该部分的中点,中点之前的节点组成左子树,中点之后的节点组成右子树,这样通过递归即可完成BST的生成。找链表中点可以用快慢指针法。具体代码:
class Solution { TreeNode* genBST(ListNode *head, ListNode *tail) { ListNode *fast = head; ListNode *slow = head; TreeNode *root = NULL; if(!head || head == tail) return NULL; while(fast != tail) { if(fast->next == tail) break; fast = fast->next->next; slow = slow->next; } root = new TreeNode(slow->val); root->left = genBST(head, slow); root->right = genBST(slow->next, tail); return root; }public: TreeNode *sortedListToBST(ListNode *head) { return genBST(head, NULL); }};
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
- hdu 1016 Prime Ring Problem
- redis列表键的底层实现之链表
- 欢迎使用CSDN-markdown编辑器
- php7/mysql/apache/windows环境搭建
- 总结一下HBase各种级别的锁以及对读写的阻塞
- [leetcode] 109. Convert Sorted List to Binary Search Tree
- Codeforces 27B Tournament(dfs,判断有向图中点的连通性)
- lua 实现类继承和覆盖
- 本地虚拟机Ubuntu14.04系统和宿主机Windows系统通信问题(java编写的socket通信)
- 笔试题:计算机网络 (1)
- Date Calender的问题
- FZU 1056扫雷游戏
- 逻辑地址、线性地址、物理地址和虚拟地址
- python的os模块fork、wait、system、exec、popen、exit函数讲解