标签:sorted new tail img slow 平衡二叉搜索树 二分 tno mst
Convert Sorted List to Binary Search Tree - LeetCode
解法一:递归,二叉搜索树的中序遍历结果刚好是一个有序数组,有序数组中间的数字刚好是根节点,因此可以用二分的思想来做。不过这道题不像数组可以直接访问中间节点,要用快慢节点的方法。
/**
* 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:
typedef TreeNode* Tnode;
typedef ListNode* Lnode;
TreeNode* sortedListToBST(ListNode* head) {
if(!head) return NULL;
return sortedListToBST(head,NULL);
}
TreeNode* sortedListToBST(Lnode head,Lnode tail) {
if(head == tail) return NULL;
Lnode slow = head, fast = head;
while(fast != tail && fast->next != tail)
{
slow = slow->next;
fast = fast->next->next;
}
Tnode n = new TreeNode(slow->val);
n->left = sortedListToBST(head,slow);
n->right = sortedListToBST(slow->next,tail);
return n;
}
};
Convert Sorted List to Binary Search Tree - LeetCode
标签:sorted new tail img slow 平衡二叉搜索树 二分 tno mst
原文地址:https://www.cnblogs.com/multhree/p/10575666.html