1、问题描述
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。样例
给出数组 [1,2,3,4,5,6,7]
,
返回
4
/ \
2 6
/ \ / \
1 3 5 7
2、实现思路
数组的中间值来作为二叉树的根节点,左子树根节点为数组第一个数值到根节点的中间值,右子树的根节点为根节点到数组最后一个只的中间值,依次进行二分。
3、代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: A sorted (increasing order) array
* @return: A tree node
*/
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
return changeTree(A,0,A.size()-1);
}
TreeNode *changeTree(vector<int> &A,int first,int last){
if(first>last){ return NULL; }
TreeNode *node =new TreeNode;
int a=(first+last)/2;
node->val=A[a];
node->left=changeTree(A,first,a-1);
node->right=changeTree(A,a+1,last);
return node;
}
};
4、感想
此二叉树进行中序遍历就是数组,依次进行二分法确定根节点。