LeetCode 中级 - 有序链表转换二叉搜索树(109)

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

采用二分的思路 将中间节点作为分割点,分成左子树和右子树。
/**
 * 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:
    vector<int> v;
    TreeNode* sortedListToBST(ListNode* head) {
    //遍历链表将值存入vector中,方便之后的查中间值操作。
while(head!=NULL) { v.push_back(head->val); head=head->next; } return dfs(0,v.size()-1); } TreeNode * dfs(int l,int r) { if(l>r) return NULL; int mid=l+(r-l)/2; TreeNode *root=new TreeNode(v[mid]); root->left=dfs(l,mid-1); root->right=dfs(mid+1,r); return root; } };


猜你喜欢

转载自www.cnblogs.com/-xinxin/p/10603393.html