标签:leetcode
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
总结:这个是网上找的,还不明白为什么是下面这个样子,去掉&,就出错
ListNode *&node
TreeNode *sortedListToBST(ListNode *head) { int len = 0; ListNode * node = head; while (node != NULL) { node = node->next; len++; } return buildTree(head, 0, len-1); } TreeNode *buildTree(ListNode *&node, int start, int end) { if (start > end) return NULL; int mid = start + (end - start)/2; TreeNode *left = buildTree(node, start, mid-1); TreeNode *root = new TreeNode(node->val); root->left = left; node = node->next; root->right = buildTree(node, mid+1, end); return root; }
TreeNode *sortedListToBST(ListNode *head) { vector<TreeNode*> treeNodes; if(head == NULL) return NULL; while (head != NULL) { TreeNode *node = new TreeNode(head->val); treeNodes.push_back(node); head = head->next; } return genBST(0, treeNodes.size()-1, treeNodes); } TreeNode* genBST(int start, int end, vector<TreeNode*> &treeNodes) { if (start == end) return treeNodes[start]; else if (start+1 == end) { treeNodes[start]->right = treeNodes[end]; return treeNodes[start]; } int mid = (start+end)/2; TreeNode* root = treeNodes[mid]; root->left = genBST(start, mid-1, treeNodes); root->right = genBST(mid+1, end, treeNodes); return root; }
总结:上面这个代码跟我参考得到的思想一致,但是我的是time limit
TreeNode *sortedListToBST(ListNode *head) { int len = 0; ListNode *node = head; while(node) { len++; node = node->next; } return BuildTree(head,1,len); } TreeNode *BuildTree(ListNode *node,int start,int end) { if(start > end) return NULL; int mid = start + (end-start)/2; ListNode *mi_node = node; for(int i=1;i<mid;i++) { mi_node = mi_node->next; } TreeNode *root = new TreeNode(mi_node->val); root->left = BuildTree(node,start,mid-1); root->right = BuildTree(node,mid+1,end); return root; }
leetcode__Convert Sorted List to Binary Search Tree,布布扣,bubuko.com
leetcode__Convert Sorted List to Binary Search Tree
标签:leetcode
原文地址:http://blog.csdn.net/xuerenlv123/article/details/32123219