LeetCode 题解(154): Convert Sorted List to Binary Search Tree

来源:互联网 发布:在哪里买淘宝小号 编辑:程序博客网 时间:2024/05/21 19:39

题目:

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

题解:

递归。

C++版:

class Solution {public:    TreeNode* sortedListToBST(ListNode* head) {        if(!head)            return NULL;        int length = 0;        ListNode* p = head;        while(p) {            p = p->next;            length++;        }        return toBST(head, length);    }        ListNode* findMid(ListNode* head, int pos) {        ListNode* p = head;        int i = 0;        while(i < pos) {            p = p->next;            i++;        }        return p;    }        TreeNode* toBST(ListNode* head, int length) {        if(length == 0) {            return NULL;        }        else if(length == 1) {            TreeNode* root = new TreeNode(head->val);            return root;        } else {            ListNode* mid = findMid(head, (length - 1) / 2);            TreeNode* root = new TreeNode(mid->val);            root->left = toBST(head, (length-  1) / 2);            root->right = toBST(mid->next, length - (length + 1) / 2);            return root;        }    }};

Java版:

public class Solution {    public TreeNode sortedListToBST(ListNode head) {        int length = 0;        ListNode p = head;        while(p != null) {            p = p.next;            length++;        }                return toBST(head, length);    }        public TreeNode toBST(ListNode head, int length) {        if(length == 0) {            return null;        } else if(length == 1) {            return new TreeNode(head.val);        } else {            ListNode mid = findMid(head, length);            TreeNode root = new TreeNode(mid.val);            root.left = toBST(head, (length - 1) / 2);            root.right = toBST(mid.next, length - (length + 1) / 2);            return root;        }    }        public ListNode findMid(ListNode head, int length) {        ListNode p = head;        int i = 0;        while(i < (length - 1) / 2) {            p = p.next;            i++;        }        return p;    }}

Python版:

class Solution:    # @param {ListNode} head    # @return {TreeNode}    def sortedListToBST(self, head):        length = 0        p = head        while p != None:            p = p.next            length += 1                    return self.toBST(head, length)            def toBST(self, head, length):        if length == 0:            return None        elif length == 1:            return TreeNode(head.val)        else:            mid = self.findMid(head, length)            root = TreeNode(mid.val)            root.left = self.toBST(head, (length - 1) / 2)            root.right = self.toBST(mid.next, length - (length + 1) / 2)            return root                def findMid(self, head, length):        p, i = head, 0        while i < (length - 1) / 2:            p = p.next            i += 1        return p

0 0
原创粉丝点击