LeetCode题解——Convert Sorted List to Binary Search Tree

来源:互联网 发布:东莞淘宝美工专业培训 编辑:程序博客网 时间:2024/05/17 01:26

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) {//O(n^2)解法        if(!head) return NULL;        //find the median of the listNode O(n)        ListNode*  MidNode = findMedianOfList(head);        TreeNode* root=new TreeNode(MidNode->val);        root->right = sortedListToBST(MidNode->next);// set MidNode to NULL get the left part of the ListListNode* phead = new ListNode(0);phead->next = head;ListNode* newhead = phead;while(newhead->next && newhead->next!=MidNode){newhead = newhead->next;}newhead->next = NULL;        root->left = sortedListToBST(phead->next);        return root;    }    ListNode* findMedianOfList(ListNode* head){        if(!head||!head->next) return head;        ListNode* fast = head, *slow = head;        while(fast && fast->next){            fast = fast->next->next;            slow = slow->next;        }        return slow;    }};


0 0
原创粉丝点击