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.
思路
取链表的中间结点做为根节点,该结点前面的链表部分做为左子树,结点后面的部分做为右子树。然后利用递归的思想,不断递归左子树和右子树。
解题
c++版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
* Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int calLen(ListNode *node) { int len = 0; while(node) { len++; node = node->next; } return len; } TreeNode *createTree(ListNode *node, int left, int right) { if (left > right) return NULL; int mid = (left + right) / 2; ListNode *p = node; for(int i = left; i < mid; i++) p = p->next; TreeNode *leftNode = createTree(node, left, mid - 1); TreeNode *rightNode = createTree(p->next, mid + 1, right); TreeNode *tNode = new TreeNode(p->val); tNode->left = leftNode; tNode->right = rightNode; return tNode; } TreeNode *sortedListToBST(ListNode *head) { int len = calLen(head); return createTree(head, 0, len - 1); } };
|
python 版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
class Solution: def sortedListToBST(self, head): len=self.calLen(head) return self.createTree(head,0,len-1) def calLen(self,head): len=0 cur=head while(cur): cur=cur.next len+=1 return len def createTree(self,head,left,right): if left>right: return None mid=(left+right)/2 p=head for i in range(left,mid): p=p.next leftNode=self.createTree(head,left,mid-1) rightNode=self.createTree(p.next,mid+1,right) tNode=TreeNode(p.val) tNode.left=leftNode tNode.right=rightNode return tNode
|