109. Convert Sorted List to Binary Search Tree
Posted 积少成多
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了109. Convert Sorted List to Binary Search Tree相关的知识,希望对你有一定的参考价值。
Given a singly linked list where elements are sorted in ascending order,
convert it to a height balanced BST.
==============
题目:将升序的链表,转化为BST(note:此BST要求是高度平衡,就是树种左右子树高度差不超过1)
思路:
def TreeNode* sortedListToBST(ListNode* head){ 按照slow/fast方式找到链表的中间节点mid, 将升序链表在mid节点处切割成为两个链表head1,和head2 将中间节点的值,new一个新的TreeNode节点:TreeNode *root = new TreeNode(head2->val) 下面开始递归: root的左子树就是sortedListToBST(head1) root的右子树就是sortedListToBST(head2->next) return root }
代码如下:
/** * 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==nullptr){ return nullptr; }else if(head->next==nullptr){ return new TreeNode(head->val); } ListNode *slow,*fast,*prev; slow = fast = head; prev = nullptr; while(fast && fast->next){ prev = slow; slow = slow->next; fast = fast->next->next; } prev->next = nullptr; //showList(head); //showList(slow); TreeNode *root = new TreeNode(slow->val); root->left = sortedListToBST(head); root->right = sortedListToBST(slow->next); return root; } };
以上是关于109. Convert Sorted List to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
109. Convert Sorted List to Binary Search Tree
109. Convert Sorted List to Binary Search Tree
109. Convert Sorted List to Binary Search Tree
109. Convert Sorted List to Binary Search Tree