标签:style blog color 使用 io ar 问题 div
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:使用两个指针分别以1、2的速度遍历链表,以定位出链表的中点,进而将链表分割成三部分:{ 前一段,中点,后一段 },分别对应所求平衡二叉搜索树的左子树、根节点以及右子树。于是,我们将问题分解为对前一段和后一段两个子链表的求解。使用递归可以很方便地实现。
1 class Solution { 2 public: 3 TreeNode *sortedListToBST( ListNode *head ) { 4 if( !head ) { return 0; } 5 return ConvertSubList( head ); 6 } 7 private: 8 TreeNode* ConvertSubList( ListNode *node ) { 9 if( !node ) { return 0; } 10 if( !node->next ) { return new TreeNode( node->val ); } 11 ListNode *slow = node, *fast = node->next; 12 while( fast->next ) { 13 fast = fast->next; 14 if( fast->next ) { slow = slow->next; fast = fast->next; } 15 } 16 TreeNode *treeNode = new TreeNode( slow->next->val ); 17 fast = slow->next->next; 18 slow->next = 0; 19 treeNode->left = ConvertSubList( node ); 20 treeNode->right = ConvertSubList( fast ); 21 return treeNode; 22 } 23 };
Convert Sorted List to Binary Search Tree,布布扣,bubuko.com
Convert Sorted List to Binary Search Tree
标签:style blog color 使用 io ar 问题 div
原文地址:http://www.cnblogs.com/moderate-fish/p/3917046.html