标签:
Given an array where elements are sorted in ascending order, convert it toa height balanced BST.
HideTags
#pragma once #include<iostream> #include<vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode *sortedArrayToBST(vector<int> &num) { if (num.size() == 0) return NULL; int size = num.size(); TreeNode* t = new TreeNode(num[size/2]); //参数为(begin,end)为两个迭代器,截取[begin,end)前开后闭子段为新的vector vector<int> n1(num.begin(), num.begin()+size/2);//前半段 vector<int> n2(num.begin() + size / 2+1, num.end());//后半段 t->left = sortedArrayToBST(n1); t->right = sortedArrayToBST(n2); return t; } void print(TreeNode* root) { if (!root) return; cout << root->val << " "; if (root->left) print(root->left); if (root->right) print(root->right); } void main() { vector<int> v = { 1, 2, 3, 4, 5, 6, 7 }; /*vector<int> v1 = { 1 }; vector<int> v2 = { }; vector<int>::iterator begain, end; vector<int> v3(v.begin(),v.end()); for (int i = 0; i < v3.size(); i++) cout << v3[i] << ' ';*/ print(sortedArrayToBST(v)); system("pause"); }
108.Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://blog.csdn.net/hgqqtql/article/details/43415815