leetcode-109 Convert Sorted List to Binary Search Tree

来源:互联网 发布:idc机房网络架构 编辑:程序博客网 时间:2024/06/14 16:57

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

使用快慢两个指针找到单链表的中间节点,作为BST的根,将左右两个单链表断开后分别递归地建立为其左右子树。

注意递归边界:单链表为空和只有一个元素时特殊处理一下。

/** * 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)            return NULL;        if(!head->next)            return new TreeNode(head->val);        ListNode* fast = head;        ListNode* slow = head;        ListNode* prev = NULL;        while(fast&&fast->next){            fast = fast->next->next;            prev = slow;            slow = slow->next;        }        TreeNode* root = new TreeNode(slow->val);        prev->next = NULL;        root->left = sortedListToBST(head);        root->right = sortedListToBST(slow->next);        return root;    }};


阅读全文
0 0
原创粉丝点击