109. Convert Sorted List to Binary Search Tree
2016-06-22 14:26
162 查看
Given a singly linked list where elements are sorted in ascending order,
convert it to a height balanced BST.
==============
题目:将升序的链表,转化为BST(note:此BST要求是高度平衡,就是树种左右子树高度差不超过1)
思路:
代码如下:
convert it to a height balanced BST.
==============
题目:将升序的链表,转化为BST(note:此BST要求是高度平衡,就是树种左右子树高度差不超过1)
思路:
def TreeNode* sortedListToBST(ListNode* head){ 按照slow/fast方式找到链表的中间节点mid, 将升序链表在mid节点处切割成为两个链表head1,和head2 将中间节点的值,new一个新的TreeNode节点:TreeNode *root = new TreeNode(head2->val) 下面开始递归: root的左子树就是sortedListToBST(head1) root的右子树就是sortedListToBST(head2->next) return root }
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedListToBST(ListNode* head) { if(head==nullptr){ return nullptr; }else if(head->next==nullptr){ return new TreeNode(head->val); } ListNode *slow,*fast,*prev; slow = fast = head; prev = nullptr; while(fast && fast->next){ prev = slow; slow = slow->next; fast = fast->next->next; } prev->next = nullptr; //showList(head); //showList(slow); TreeNode *root = new TreeNode(slow->val); root->left = sortedListToBST(head); root->right = sortedListToBST(slow->next); return root; } };
相关文章推荐
- BeautifulSoup 解析html方法(爬虫)
- 关于Scroller的使用以及自己实现一个侧滑菜单
- .NET Core 使用Dapper 操作MySQL
- 用flex做垂直居中
- 【linux】grub加密
- iOS识别二维码
- java加密字符串
- applicationContext.xml详解
- Visual Studio创建项目提示错误
- C#复习⑧
- 在linux上用dd命令实现ghost功能
- Celery 使用简介
- c#中控制不能从一个case标签贯穿到另一个case标签
- #ubuntu# ubuntu 下安装 phpstorm
- Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled.
- android 线程那点事
- android 线程那点事
- android 线程那点事
- openwrt linux makefile
- 异步任务神器 Celery 简明笔记