The main idea is similar to the middle-order traversal. First, we construct the left subtree, then the current node, and then the right subtree.
TreeNode *sortedListToBST(ListNode *head) { int count = 0; ListNode * cur = head; while (cur) { count++; cur = cur->next; } return sortedListToBST(head, count); } TreeNode *sortedListToBST(ListNode * (&head), int count) { if (count <= 0) return NULL; TreeNode* left = sortedListToBST(head, count / 2 ); TreeNode * root = new TreeNode(head->val); head = head->next; root->left = left; root->right = sortedListToBST(head, count - (count / 2) - 1); return root; }
Another similar question: converting a binary search tree into a two-way linked list
Similar to the central traversal, the left subtree is converted into a two-way linked list first, and then the right subtree is processed.
The Code is as follows:
void BSTToList(TreeNode * t, ListNode * &l){if (t->left) BSTToList(t->left, l);ListNode * cur = new ListNode(t->val);cur->left = l;if (!l) l->right = cur;l = cur;if (t->right) BSTToList(t->right, l);}
Convert sorted list to binary search tree [leetcode] O (n) Algorithm