首页 > 代码库 > leetcode__Convert Sorted List to Binary Search Tree
leetcode__Convert Sorted List to Binary Search Tree
Convert Sorted List to Binary Search Tree
Total Accepted: 12283 Total Submissions: 45910My SubmissionsGiven 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。