有序数组构建平衡二叉树

#include <stdio.h>

TreeNode *sortedArrayToBST(vector<int> &num){
	if(num.size()==0)
		return NULL;
	if(num.size()==1){
		TreeNode*parent =new TreeNode(num[0]);
		return parent;
	}
	int first=0;
	int last=(int)num.size()-1;
	return helper(num,first,last);
}

TreeNode* helper(vector<int>num,int first,int last){
	if(first>last){
		return NULL;
	}
	if(first==last){
		TreeNode* parent=new TreeNode(num[first]);
		return parent;
	}
	int mid=(first+last)/2;
	TreeNode*leftchild=helper(num,first,mid-1);
	TreeNode*righttchild=helper(num,mid+1,last);
	TreeNode *parent=new TreeNode(num[mid]);
	parent->left=leftchild;
	parent->right=rightchild;
	return parent;
}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/jwy2014/article/details/79944866
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞