Convert Sorted List to Binary Search Tree
Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Problem Solving Ideas:
Test instructions is a binary lookup tree that constructs an ordered list. The method of finding the middle node is using a double-pointer approach. Note that we also need to save the previous node of the middle node, so that a linked list can be divided into two linked lists. Note that the 38 line is to restore the linked list to its original appearance.
/** * 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) {if (head = = null) {return null; } listnode* Myhead = new ListNode (0); Myhead->next = head; listnode* pre = Myhead; listnode* one = head, *two = head; while (Two->next!=null && two->next->next!=null) {pre = pre->next; one = one->next; both = two->next->next; } one->next; Pre->next = NULL; treenode* root = new TreeNode (one->val); Root->left = Sortedlisttobst (Myhead->next); Root->right = Sortedlisttobst(a); Pre->next = one; Restore the linked list structure//delete one; Why can't I delete it here? Delete Myhead; return root; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Convert Sorted List to Binary Search Tree