[Leetcode] 109. Convert Sorted List to Binary Search Tree 解题报告

来源:互联网 发布:淘宝技歌膏是真的假的 编辑:程序博客网 时间:2024/06/02 02:44

题目

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

思路

1、预先计算长度:我们可以采用线性扫描的方法获得链表长度,然后采用中序构造的方法来生成BST:即首先生成左子树,然后生成根节点,最后生成右子树。这是因为采用中序生成时,树节点的构造次序刚好和链表的遍历次序是一致的,因此我们可以维护一个全局的链表节点,随着该节点的推进,逐步构造出BST。具体请见代码片段1。

2、不预先计算长度:还记得处理链表问题的神器把?Two Pointers!在这里我们可以采用Two pointers的思路获得链表的中点,然后生成根节点,接着就可以采用递归的方式分别构造左子树和右子树了。这里特别需要注意递归的边界条件。另外这种方法对原有链表也有所破坏。如果面试官不允许对原始链表进行破坏,则建议采用思路1。

代码

1、预先计算长度:

/** * 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 == NULL)            return NULL;        int size = getSize(head);        current_node = head;        return constructTree(size);    }private:    TreeNode* constructTree(int size) {        if(size <= 0) {            return NULL;        }        TreeNode* left = constructTree(size / 2);        TreeNode* root = new TreeNode(current_node->val);        current_node = current_node->next;        TreeNode* right = constructTree(size - size / 2 - 1);        root->left = left;        root->right = right;        return root;    }    int getSize(ListNode* head) {        int size = 0;        while(head){            ++size;            head = head->next;        }        return size;    }    ListNode *current_node;};

2、不预先计算长度:

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