标签:
一般我解题都是用的头递归或者尾递归。第一次
见识到了中递归,相当于把递归当成了一个循环体,用引用来作为变量,每一个递归中改动,须要非常强大的想象力。把整个递归树在脑子里想清楚。空间和时间都为O(n):
TreeNode *sortedListToBST(ListNode *head) { vector<TreeNode*> treeNodes; 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; }
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; }解法引用:http://www.bwscitech.com/a/jishuzixun/javayuyan/2013/0930/15822.html
Convert Sorted List to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/yxwkf/p/5205180.html