Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
基本思路:
中序遍历的过程,与有序链表的顺序是一一对应的。
采用中序遍历构造进树的构造。
并利用取值范围,确定,根的位置,以及子树的范围。
故需要遍历整个链表,求得总的长度。
链表长度的一半,即为根结点所在位置。 左边则为左子树的取值范围,右边即为右子树的取值范围。
同上,递归应用到左子树,右子树。逐步缩范围,直到叶节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedListToBST(ListNode* head) { int size = 0; ListNode *p = head; while (p) { ++size; p = p->next; } return helper(head, 0, size-1); } TreeNode *helper(ListNode *&head, int start, int stop) { if (start > stop) return 0; const int mid = start + (stop-start) / 2; TreeNode *left = helper(head, start, mid-1); TreeNode *root = new TreeNode(head->val); root->left = left; head = head->next; root->right = helper(head, mid+1, stop); return root; } };
Convert Sorted List to Binary Search Tree -- leetcodeGiven a singly linked list where elements are s
原文地址:http://blog.csdn.net/elton_xiao/article/details/45599721