1.Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
2.Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Here are two questions. are two questions connected together. Give you an array or list of sequential (ascending) rows, converting them into a balanced binary tree. If it's not orderly. A set of randomly entered data, you must use the RBT or AVL tree, so the operation will become more complex. It involves rotation, but it's lined up here. So, just find the median. As the root, and then recursively constructs the left and right sub-trees according to the median number.
The two ideas are the same as above, the only difference is that the list to find the median is a bit troublesome. You need to introduce fast, slow two pointers to find the median. The code is as follows:
1.Array
Class Solution {public: TreeNode *tree (int left, int. right, vector<int> &num) { TreeNode *root = null;
if (left <= right) { int. cen = (left + right)/2; root = new TreeNode (Num[cen]); Root->left = Tree (left, cen-1, num); Root->right = Tree (cen + 1, right, num); } return root; } TreeNode *sortedarraytobst (vector<int> &num) { TreeNode *t = NULL; int N = Num.size (); T = Tree (0, N-1, num); return T; };
2.link-list
Class Solution {Public:listnode *findmid (ListNode *head) {//Here is assumed to have only two digits in the list. Then mid returns the Head->next. if (head = = NULL | | head--NEXT = null) return head; ListNode *fast, *slow, *pre; Fast = slow = head; Pre = NULL; while (Fast && fast->next) {pre = slow; slow = slow->next; Fast = fast->next->next; } pre->next = NULL; return slow; } TreeNode *buildtree (ListNode *head) {TreeNode *root = NULL; ListNode *mid = NULL; if (head) {mid = Findmid (head); root = new TreeNode (mid->val); if (head! = mid) {Root->left = Buildtree (head); Root->right = Buildtree (Mid->next); }} return root; } TreeNode *sortedlisttobst (ListNode *head) {TreeNode *t; T = Buildtree (head); return T; }};
Leetcode:: Convert Sorted Array (link list) to Binary Search tree [tree]