77:Convert Sorted List to Binary Search Tree

来源:互联网 发布:网络军事评论员 编辑:程序博客网 时间:2024/05/17 09:06

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

解析1:可以采用和转换有序数组到二分查找树这一问题相同的解法,先构造根节点,然后再构造其左右树的结点,该方法被称之为自顶向下法,但是需要注意的是单链表不能随机访问,代码如下:

// 自顶向下,时间复杂度 O(nlogn),空间复杂度 O(logn)class Solution {public:        TreeNode* sortedListToBST(ListNode* head) {                return sortedListToBSL(head, listLength(head));        }        TreeNode* sortedListToBST(ListNode* head, int len) {                if (len == 0) return nullptr;                if (len == 1) return new TreeNode(head -> val);                TreeNode* root = new TreeNode(nth_node(head, len / 2 + 1) -> val);                root -> left = sortedListToBST(head, len / 2);                root -> right = sortedListToBST(nth_node(head, len / 2 + 2), (len - 1) / 2);                return root;        }        int listLength(ListNode* node) {                int n = 0;                while (node) node = node -> next, ++n;                return n;        }        ListNode* nth_node(ListNode* node, int n) {                while (--n)                        node = node -> next;                return node;        }};

解析2:也可以采用自底向上法,即先构造左子树,然后再构造根节点,最后构造右子树,该方法时间复杂度为 O(n),代码如下:

// 自底向上,时间复杂度 O(n),空间复杂度 O(logn)class Solution {public:        TreeNode* sortedListToBST(ListNode* head) {                int len = 0;                ListNode* p = head;                while (p) {                        len++;                        p = p -> next;                }                // [0, len)                return sortedListToBST(head, 0, len);        }private:        // [start, end)        TreeNode* sortedListToBST(ListNode*& list, int start, int end) {                if (start == end) return nullptr;                int mid = start + (end - start) / 2;                TreeNode* leftChild = sortedListToBST(list, start, mid);                TreeNode* parent = new TreeNode(list -> val);                parent -> left = leftChild;                list = list -> next;                parent -> right = sortedListToBST(list, mid + 1, end);                return parent;        }};
1 0
原创粉丝点击