Convert Sorted List to Binary Search Tree问题及解法

来源:互联网 发布:mysql 修改字段长度 编辑:程序博客网 时间:2024/06/17 17:14

问题描述:

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


问题分析:

可以考虑先把链表中的元素存到vector中,然后再按照有序数组构造平衡二叉树的方法求解即可。


过程详见代码:

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


原创粉丝点击