Leetcode #109 Convert Sorted List to Binary Search Tree
2015-08-08 16:43
555 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Difficulty:Medium
Difficulty:Medium
TreeNode* sortedListToBST(ListNode* head) { TreeNode* root; if(head==NULL) return NULL; if(head->next==NULL) { root = new TreeNode(head->val); return root; } ListNode* p = head; ListNode* pNext = p; ListNode* pre = p; while(pNext->next!=NULL&&pNext->next->next!=NULL){ pre = p; p = p->next; pNext = pNext->next->next; } root = new TreeNode(p->val); p = p->next; pre->next = NULL; if(root->val == head->val) head = NULL; root->left = sortedListToBST(head); root->right = sortedListToBST(p); return root; }
相关文章推荐
- Android四大组件之BroadCast(续)
- cocos2d-x综述(源自cocos2d-x中文网)
- C++面向对象程序设计 笔记3 (面向对象部分)
- OS-8
- codeforces535C:Tavas and Karafs(二分)
- OC-@property后的修饰符及其用法小结
- Linux根文件系统详解
- 每天学点java—Object类
- 黑马程序员-----Java基础-----数组!
- JAVA学习笔记(五)
- 关系模型基本概念
- UVA 10441 Catenyms【欧拉路】
- CodeForces 492B
- 极简三位数加减出题软件
- IIS6 + PHP 访问页面出现:需要进行身份验证的问题
- 关于自定义标签当中的unable to find setter method for attribute:xxx错误 小记
- Android widget 之RemoteView
- darknet 编译与使用
- gstreamer1.2.4安装
- Intellij IDEA创建Maven Web项目以及ubuntu maven环境安装配置