Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
给定一个已排序的数组(不存在重复元素),将它转换成一棵平衡二叉搜索树。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *build(vector<int>&num, int low, int high){ if(low>high)return NULL; int mid = (low+high)/2; //生成根节点 TreeNode*root=(TreeNode*)malloc(sizeof(TreeNode)); root->val=num[mid]; //生成左子树 TreeNode*left=build(num, low, mid-1); //生成右子树 TreeNode*right=build(num, mid+1, high); //构造二叉树 root->left=left; root->right=right; return root; } TreeNode *sortedArrayToBST(vector<int> &num) { int size=num.size(); if(size==0)return NULL; return build(num, 0, size-1); } };
LeetCode: Convert Sorted Array to Binary Search Tree [108],布布扣,bubuko.com
LeetCode: Convert Sorted Array to Binary Search Tree [108]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/28384079