Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
structListNode {intVal; ListNode*Next; ListNode (intx): Val (x), Next (NULL) {}};structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: TreeNode*sortedlisttobst (ListNode *head) { if(!head)returnNULL; intSize =1; ListNode* ListNode = head->Next; while(listnode) {size++; ListNode= listnode->Next; } TreeNode* Root =NewTreeNode (0); BinarySearch (Head,size,root); returnRoot; } voidBinarySearch (ListNode *head,intSize, treenode* TreeNode)//binary method, for array, need one end of two pointers; For list, the head pointer and size are required. { if(Size = =1) {TreeNode->val = head->Val; return; } ListNode* ListNode =Head; intMID = Size>>1; for(inti =1; i<mid;i++) {ListNode= ListNodeNext; } TreeNode->val = listnode->next->Val; ListNode* Head2 = listnode->next->Next; ListNode->next =NULL; TreeNode->left =NewTreeNode (0);//Application number space, and then transfer. Otherwise, the change in the value of the pointer itself in the called function does not affect the callerBinarySearch (head,mid,treenode->Left ); if(head2) {TreeNode->right =NewTreeNode (0); BinarySearch (Head2,size-mid-1,treenode->Right ); } }};
It can also be passed by reference, so that it does not need to be initialized first.
classSolution { Public: TreeNode*sortedlisttobst (ListNode *head) { if(!head)returnNULL; intSize =1; ListNode* ListNode = head->Next; while(listnode) {size++; ListNode= listnode->Next; } TreeNode* Root =NewTreeNode (0); BinarySearch (Head,size,root); returnRoot; } voidBinarySearch (ListNode *head,intSize, treenode* &treenode)//passing parameters by reference { if(Size = =1) {TreeNode=NewTreeNode (head->val); return; } ListNode* ListNode =Head; intMID = Size>>1; for(inti =1; i<mid;i++) {ListNode= ListNodeNext; } TreeNode=NewTreeNode (Listnode->next->val);//in the application space for the use of applicationslistnode* head2 = listnode->next->Next; ListNode->next =NULL; BinarySearch (Head,mid,treenode->left);//referring to the address of 0x0000 if(head2) {BinarySearch (head2,size-mid-1,treenode->Right ); } }};
Note that NULL is a macro definition
#define NULL 0
That is, NULL = (void*) 0
109. Convert Sorted list to Binary Search Tree (list; Divide-and-conquer, DFS)