标签:style blog io ar color sp for 数据 on
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析:我们比较熟悉由一个sorted array生成一个BST,不同的是这里的数据结构换为了linked list。我们同样可以用递归的方法生成BST,与数组不同的是我们需要先确定linked list的中间结点。
class Solution { public: TreeNode *sortedListToBST(ListNode *head) { if(head == NULL) return NULL; if(head->next == NULL){ TreeNode *root = new TreeNode(head->val); return root; } //get length int n = 0; for(ListNode *p = head; p; p = p->next) n++; //find middle point ListNode *prev = NULL, *mid = head; for(int i = 0; i < (n-1)/2; i++){ prev = mid; mid = mid->next; } TreeNode *root = new TreeNode(mid->val); if(prev) prev->next = NULL; if(mid != head) root->left = sortedListToBST(head); root->right = sortedListToBST(mid->next); return root; } };
Leetcode: Convert Sorted List to Binary Search Tree
标签:style blog io ar color sp for 数据 on
原文地址:http://www.cnblogs.com/Kai-Xing/p/4121848.html