您的位置:首页 > 其它

Leetcode | Convert Sorted Array to Binary Search Tree

2014-06-12 16:38 281 查看
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 *sortedArrayToBST(vector<int> &num) {
return recursive(num, 0, num.size() - 1);
}

TreeNode *recursive(vector<int> &num, int s, int e) {
if (s > e) return NULL;
int mid = (s + e) / 2;
TreeNode* root = new TreeNode(num[mid]);
root->left = recursive(num, s, mid - 1);
root->right = recursive(num, mid + 1, e);
return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: