1. Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
2. Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
The two questions are connected together. You can use an array or linked list in ascending order to convert them into a balanced binary tree. If the order is not arranged, the RBT or AVL tree must be used for a group of random input data. This makes the operation more complex and involves rotation, but the order is arranged here. Therefore, we only need to find the median as the root and recursively construct the Left and Right Subtrees Based on the left and right columns of the median;
The idea of the two questions is described above. The only difference is that it is troublesome to search for the median in the linked list. We need to introduce the fast and slow 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) {// if there are only two numbers in the linked list, the Mid Returns 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;} Pre-> next = NULL; return slow;} treenode * buildtree (listnode * head) {treenode * root = NULL; listnode * m Id = 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]