码迷,mamicode.com
首页 > 其他好文 > 详细

108.Convert Sorted Array to Binary Search Tree

时间:2015-02-02 23:14:33      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

Given an array where elements are sorted in ascending order, convert it toa height balanced BST.

HideTags

 Tree  Depth-first Search




#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!