Convert sorted list to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
In order to meet the balance requirements, it is easy to think of an intermediate node as the root of the tree. Because it has been sorted, the left and right sides naturally meet the requirements of BST.
The left and right substrings are recursive, and the upper root node can be connected to the lower root node.
For details, see the code and comments.
/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; * // *** definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x): Val (x ), left (null), right (null) {}*}; */class solution {public: treenode * sortedlisttobst (listnode * head) {If (Head = NULL) {// empty return nu Ll;} else if (Head-> next = NULL) {// a node treenode * root = new treenode (Head-> Val); Return root ;} else {listnode * mid = findmid (head); // locate the intermediate node as the root node (meeting the balance requirements) listnode * lefthead = head; // The left child string header node is the original linked list header node listnode * righthead = mid-> next; // The right substring header node is the next node of the intermediate node treenode * root = new treenode (mid-> Val ); // recursively go to root-> left = sortedlisttobst (lefthead); root-> right = sortedlisttobst (righthead); Return Root ;}} Listnode * findmid (listnode * head) {// the prerequisite for calling is head! = NULL // If the linked list is an even number, the pointer to the second half of the sub-string is returned. If the linked list is an odd number, the listnode * pre = NULL pointer to the intermediate node is returned; listnode * fast = head; listnode * slow = head; while (fast! = NULL) {fast = fast-> next; If (fast! = NULL) {fast = fast-> next; Pre = slow; slow = slow-> next;} Pre-> next = NULL; // return slow ;}};
[Leetcode] convert sorted list to Binary Search Tree