标签:
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: vector<int> list; TreeNode* makeTree(int start,int end) { if(start>end) return NULL; int mid=(start+end)/2; TreeNode* root=new TreeNode(list[mid]); TreeNode* left=makeTree(start,mid-1); TreeNode* right=makeTree(mid+1,end); root->left=left; root->right=right; return root; } TreeNode* sortedListToBST(ListNode* head) { if(head==NULL) return NULL; ListNode* p=head; while(p) { list.push_back(p->val); p=p->next; } return makeTree(0,list.size()-1); } };
class Solution { public: int length(ListNode* head) { int len=0; ListNode* p=head; while(p) { len++; p=p->next; } return len; } TreeNode* makeTree(ListNode* head,int start,int end) { if(start>end) return NULL; int mid=(start+end)/2; ListNode* p=head; for(int i=start;i<mid;i++) { p=p->next; } TreeNode* root=new TreeNode(p->val); TreeNode* left=makeTree(head,start,mid-1); TreeNode* right=makeTree(p->next,mid+1,end); root->left=left; root->right=right; return root; } TreeNode* sortedListToBST(ListNode* head) { if(head==NULL) return NULL; ListNode* p=head; int len=length(p); return makeTree(p,0,len-1); } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
Convert Sorted List to Binary Search Tree
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/47091419