convert-sorted-list-to-binary-search-tree
来源:互联网 发布:淘宝老客户刷销量 编辑:程序博客网 时间:2024/06/16 22:41
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/** * 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: TreeNode *sortedListToBST(ListNode *head) { if(head==NULL) return NULL; return recurbuild(head); } TreeNode *recurbuild(ListNode* head) { if(head==NULL) return NULL; if(head->next==NULL) { return new TreeNode(head->val); } ListNode* sav=head; ListNode* mid=head; ListNode* pre=mid; while(head&&head->next) { head=head->next->next; pre=mid; mid=mid->next; } pre->next=NULL; TreeNode* temp=new TreeNode(mid->val); temp->left=sortedListToBST(sav); temp->right=sortedListToBST(mid->next); return temp; }};
0 0
- 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
- UIFragment的使用
- 安装Laravel elixir 并解决安装过程中的报错
- 栈溢出几种保护方式
- 如何面试测试工程师?
- BZOJ 1270: [BeijingWc2008]雷涛的小猫 傻逼DP
- convert-sorted-list-to-binary-search-tree
- [LeetCode]26. Remove Duplicates from Sorted Array
- 数据库知识总结
- ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
- Problem D: C++习题-快速排序
- PAT(Python)-1030:完美数列(25)
- [OpenGL] 游戏开发的简单demo
- highcharts坐标轴实现html里的title效果
- VMware安装Ubuntu虚拟机后的相关必备操作