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); } };