leetcode 109 Convert Sorted List to Binary Search Tree
2016-06-07 20:28
429 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
/**
* 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 *buildTree(ListNode *&head, int left, int right) {
if(left > right) {
return NULL;
}
int mid = left+(right-left+1)/2;
TreeNode *leftNode = buildTree(head, left, mid-1);
TreeNode *root = new TreeNode(head->val);
head = head->next;
root->left = leftNode;
TreeNode *rightNode = buildTree(head, mid+1, right);
root->right=rightNode;
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
TreeNode *root=NULL;
if(head==NULL) return root;
ListNode *l = head;
int cnt = 0;
while(l!=NULL) {
cnt++;
l=l->next;
}
root = buildTree(head, 0, cnt-1);
return root;
}
};
Subscribe to see which companies asked this question
/**
* 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 *buildTree(ListNode *&head, int left, int right) {
if(left > right) {
return NULL;
}
int mid = left+(right-left+1)/2;
TreeNode *leftNode = buildTree(head, left, mid-1);
TreeNode *root = new TreeNode(head->val);
head = head->next;
root->left = leftNode;
TreeNode *rightNode = buildTree(head, mid+1, right);
root->right=rightNode;
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
TreeNode *root=NULL;
if(head==NULL) return root;
ListNode *l = head;
int cnt = 0;
while(l!=NULL) {
cnt++;
l=l->next;
}
root = buildTree(head, 0, cnt-1);
return root;
}
};
相关文章推荐
- 单链表排序之直接插入排序
- 32. Longest Valid Parentheses
- 13周 阅读项目(3)
- Android之解决远程拍照不打开activity用其它方式获取surfaceView
- extjs ajax java简单精美验证码实现 有图
- Java 2D API - 1. 基本概念
- Git SSH Key 生成步骤
- Tomcat如何禁用session(Turn off the Session in Tomcat )
- 1724: [Usaco2006 Nov]Fence Repair 切割木板
- 51NOD 1259 整数划分 (五边形定理)
- 集合
- 第九周项目一深复制体验(3)
- 红黑树详解
- ActiveMQ实例1--简单的发送和接收消息
- Python正则表达式模块re
- Major GC和Full GC的区别是什么?触发条件呢?
- 鼠标事件!
- 乐学成语——显示所有动物类成语的列表
- SpringMvc+Spring+MyBatis+Maven整合
- Debug