Convert Sorted List to Binary Search Tree
来源:互联网 发布:数据库与缓存保持一致 编辑:程序博客网 时间:2024/06/18 15:45
题目:Convert Sorted List to Binary Search Tree
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 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 *createBST(ListNode *start, ListNode * end){//主要思想:使用快慢指针实现查找中间节点的操作,然后将中间节点作为根节点即可 TreeNode *root; if(start==end){ root=new TreeNode(start->val); return root; } ListNode *pre=NULL; ListNode *s=start; ListNode *q=start; while(q!=end && q->next && q->next!=end){ pre=s; s=s->next; q=q->next->next; } root=new TreeNode(s->val); if(pre) root->left=createBST(start, pre); if(s->next) root->right=createBST(s->next, end); return root; } TreeNode* sortedListToBST(ListNode* head) { if(head==NULL){ return NULL; } ListNode *end=head; while(end->next){ end=end->next; } TreeNode *root=createBST(head, end); return root; }};
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
- IOS的生命周期问题
- 再谈如何将android studio项目转换成eclipse
- Ecache配置文件
- 软件工程师能力自我评价表
- 测试jbpm6.2使用的基础类
- Convert Sorted List to Binary Search Tree
- 在ubuntu中用apt-get安装LEMP栈(linux+nginx+mysql+php)
- 123
- poj 1077 八数码
- 色彩心理
- SSH学习 Hibernate 多对多
- 2015 多校第四场 XYZ and Drops
- cacti安装记录 第四阶段cacti的基本使用(2)Monitor插件的使用
- 机试算法讲解: 第9题 查找,对了,当然有哨兵