标签:
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) { if(head==NULL) return NULL; vector<int> v; ListNode* p=head; while(p) { v.push_back(p->val); p=p->next; } return BuildTree(v,0,v.size()-1); } TreeNode* BuildTree(vector<int>& nums,int first,int end) { if(first>end)return NULL; if(first==end)return new TreeNode(nums[first]); int mid=(first+end)/2; TreeNode* root=new TreeNode(nums[mid]); root->left=BuildTree(nums,first,mid-1); root->right=BuildTree(nums,mid+1,end); return root; } };
leetcode No109. Convert Sorted List to Binary Search Tree
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52296942