Topic Connection
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
Convert Sorted List to Binary Search treedescription
Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; *//** * Defini tion 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) return null;vector<int> tmp; Tmp.push_back (0); while (head) {tmp.push_back (head->val); head = Head->next;} function<treenode* (int, int) > DFS = [&dfs, &tmp] (int lb, int ub), treenode* {if (lb > UB) return NUL L;int m = (lb + ub) >> 1;auto p = new TreeNode (tmp[m]);p->left = DFS (lb, m-1);p->right = DFS (M + 1, UB); Retu RN p;}; Return DFS (1, tmp.size ()-1);}};
Leetcode 109 Convert Sorted List to Binary Search Tree