Leetcode DFS convert sorted list to Binary Search Tree

Source: Internet
Author: User

Convert sorted list to binary search tree total accepted: 21420 total submissions: 78476my submissions

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.



Change an ordered single-chain table to a binary search tree
Ideas:
Using the chain table center as the root of a binary tree,
The first half of the linked list is the left subtree and the second half is the right subtree.
Recursive Implementation
Complexity: time O (N * log n), Space O (log n)

TreeNode * dfs(ListNode *head, int size){if(size <= 0) return NULL;if(size == 1) return new TreeNode(head->val);ListNode *cur = head;for(int i = 0; i < size/2; ++i){cur = cur->next;}TreeNode *root = new TreeNode(cur->val);root->left = dfs(head, size/2);root->right = dfs(cur->next, size - size/2 - 1 );return root;}TreeNode *sortedListToBST(ListNode *head) {ListNode *cur = head;int size = 0;while(cur){++size;cur = cur->next;}return dfs(head, size);}


Leetcode DFS convert sorted list to Binary Search Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.