现在的位置: 首页 > 综合 > 正文

Convert Sorted Array to Binary Search Tree

2018年04月29日 ⁄ 综合 ⁄ 共 732字 ⁄ 字号 评论关闭
#include <iostream>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
	
	TreeNode* createbst(vector<int> &a, int lhs, int rhs)
	{
		if(lhs <= rhs)
		{
			int mid = (lhs + rhs) >> 1;
			TreeNode *root = new TreeNode(a[mid]);
		
			root->left = createbst(a, lhs, mid-1);
			root->right = createbst(a, mid+1, rhs);
			return root;
		}	
		return 0;
	}

    TreeNode *sortedArrayToBST(vector<int> &num) 
	{        
		int len = num.size();
        return createbst(num, 0, len - 1);
    }
    
    void print(TreeNode *root)
    {
    	if(!root)
    		return;
   		else
   		{
			print(root->left);
		   	cout << root->val << endl;
			print(root->right);   	
	   	}
    }
};

int main(void)
{
	int a[] = {
		1, 2, 3, 4, 5, 6, 7, 8, 9
	};
	int len = sizeof(a) / sizeof(int);
	vector<int> v(a, a + len);
	
	Solution s;
	
	TreeNode* p = s.sortedArrayToBST(v);
	s.print(p);
	
	return 0;
}

抱歉!评论已关闭.