Convert Sorted Array to Binary Search Tree
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 *create(vector<int> &num,int begin,int end) { if(begin>end) return NULL; int mid; mid=(end+begin)/2; TreeNode *leftNode=create(num,begin,mid-1); TreeNode *rightNode=create(num,mid+1,end); TreeNode *node = new TreeNode(num[mid]); node->left=leftNode; node->right=rightNode; return node; } TreeNode *sortedArrayToBST(vector<int> &num) { return create(num,0,num.size()-1); } };
版权声明:本文为博主原创文章,未经博主允许不得转载。