leetcode_question_109 Convert Sorted List to Binary Search Tree
来源:互联网 发布:vmware桥接网络设置 编辑:程序博客网 时间:2024/05/01 09:48
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Recursive:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void findmid(ListNode* head, ListNode* end, ListNode* &mid) {if(head == NULL){mid=NULL; return;}if(head->next == end){mid=head; return;}ListNode* pre = head;mid = head;while(pre->next != end){pre = pre->next;if(pre->next != end) pre= pre->next;else break;mid = mid->next;}}TreeNode *tobst(ListNode* head, ListNode* tail){if(head == tail)return NULL;if(head->next == tail){int val = head->val;delete head;return new TreeNode(val);}ListNode* mid;findmid(head, tail, mid);TreeNode* tmp = new TreeNode(mid->val);tmp->left = tobst(head, mid);if(mid->next)tmp->right = tobst(mid->next, tail);delete mid;return tmp;}TreeNode *sortedListToBST(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() functionif(head==NULL)return NULL; return tobst(head,NULL); }};
- leetcode_question_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
- 位图法
- linux 常用网络工具
- 把递归转变成循环
- 2013 ACM/ICPC Asia Regional Changsha Online - I Grand Prix
- 要被毕业了,要被工作了???
- leetcode_question_109 Convert Sorted List to Binary Search Tree
- 糗大了,java中的对象和值是不一样的
- Redesign Your App for iOS 7 之 页面布局
- Access转mysql(wordpress 转库)
- poj2955
- 初学者学Java(七)
- 当你的程序在朋友的机器上显示丢失msvcr100d.dll的时候
- Red Hat AS4-Update5 ISO [i386和x86_64]下载
- 阿里巴巴2013年算法笔试题