[leetcode] 109.Convert Sorted List to Binary Search Tree

来源:互联网 发布:云计算公司排名 编辑:程序博客网 时间:2024/06/05 00:38

题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题意:
给定一个单链表,单链表的元素有序递增,转化为一颗高度平衡的二叉搜索树。
思路:
这道题只需要将这个单链表转化为一个数组,然后使用108题的代码即可。

代码如下:

/** * 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;        vector<int> nums;        while(head != NULL){            nums.push_back(head->val);            head = head->next;        }        return buildBST(nums,0,nums.size() - 1);    }    TreeNode* buildBST(vector<int>& nums,int start,int end) {        if(start > end)return NULL;        int index = (start + end)/2;        TreeNode* root = new TreeNode(nums[index]);        root->left = buildBST(nums,start,index - 1);        root->right = buildBST(nums,index + 1, end);        return root;    }};
0 0